Skip to content

Commit 36509dd

Browse files
committed
properly handle security scoped file urls
1 parent c44ff28 commit 36509dd

File tree

1 file changed

+38
-1
lines changed

1 file changed

+38
-1
lines changed

Mage/AttachmentCreationCoordinator.swift

Lines changed: 38 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -620,8 +620,45 @@ extension AttachmentCreationCoordinator: UIImagePickerControllerDelegate {
620620
extension AttachmentCreationCoordinator: UIDocumentPickerDelegate {
621621
func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
622622
for url in urls {
623+
let securityScoped = url.startAccessingSecurityScopedResource()
624+
625+
let dateFormatter = DateFormatter();
626+
dateFormatter.dateFormat = "yyyyMMdd_HHmmss";
627+
623628
let uttype = try? url.resourceValues(forKeys: [.contentTypeKey]).contentType
624-
addAttachmentForSaving(location: url, contentType: uttype?.preferredMIMEType ?? (UTType.item.preferredMIMEType ?? ""))
629+
630+
let fileType = uttype?.preferredFilenameExtension ?? url.pathExtension
631+
let mimeType = uttype?.preferredMIMEType ?? UTType.data.identifier
632+
633+
guard let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else {
634+
MDCSnackbarManager.default.show(MDCSnackbarMessage(text: "Could not access the documents directory"))
635+
return;
636+
}
637+
let attachmentsDirectory = documentsDirectory.appendingPathComponent("attachments")
638+
let urlWithoutExtension = url.deletingPathExtension()
639+
let filename = urlWithoutExtension.lastPathComponent
640+
let fileToWriteTo = attachmentsDirectory.appendingPathComponent("MAGE_\(filename)_\(dateFormatter.string(from: Date())).\(fileType)");
641+
642+
do {
643+
try FileManager.default.createDirectory(at: fileToWriteTo.deletingLastPathComponent(), withIntermediateDirectories: true, attributes: [.protectionKey : FileProtectionType.complete]);
644+
645+
guard let attachmentData = try? Data(contentsOf: url) else { return }
646+
647+
do {
648+
try attachmentData.write(to: fileToWriteTo, options: .completeFileProtection)
649+
self.addAttachmentForSaving(location: fileToWriteTo, contentType: mimeType)
650+
} catch {
651+
print("Unable to write file \(fileToWriteTo): \(error)")
652+
MDCSnackbarManager.default.show(MDCSnackbarMessage(text: "Error adding attachment \(error)"))
653+
}
654+
655+
} catch {
656+
MDCSnackbarManager.default.show(MDCSnackbarMessage(text: "Error creating directory path \(fileToWriteTo.deletingLastPathComponent()): \(error)"))
657+
}
658+
659+
if securityScoped {
660+
url.stopAccessingSecurityScopedResource()
661+
}
625662
}
626663
}
627664
}

0 commit comments

Comments
 (0)