概要
- iOS 13以降では、
UIDocumentPickerViewControllerでdocumentTypesにkUTTypeFolderを指定すると、フォルダを選択させることが可能になっている。 - 選択されたフォルダに対して
startAccessSecurityScopedResourceを呼び出すと、そのフォルダの下にファイルを書き込むことができる。
Permissionの設定
App Sandboxで「User Selected File」を「Read/Write」に設定する。
UIDocumentPickerViewControllerで書き込み先フォルダを選ぶ
iOS 13以降ではUIDocumentPickerViewControllerでdocumentTypesにkUTTypeFolderを指定することで、フォルダの選択が可能となっている。
import MobileCoreServices // kUTTypeFolderを参照するために必要
...
let documentPicker = UIDocumentPickerViewController(documentTypes: [kUTTypeFolder as String], in: .open)
documentPicker.delegate = self
present(documentPicker, animated: true, completion: nil)
選択されたディレクトリの下にファイルを書き込む
func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
guard let directoryURL = urls.first else {
return
}
debugPrint(directoryURL)
guard directoryURL.startAccessingSecurityScopedResource() else {
// Handle the failure here.
return
}
defer { directoryURL.stopAccessingSecurityScopedResource() }
do {
try "Hello World".write(to: directoryURL.appendingPathComponent("hello.txt"), atomically: true, encoding: .utf8)
try "Good Morning".write(to: directoryURL.appendingPathComponent("morning.txt"), atomically: true, encoding: .utf8)
} catch let error {
debugPrint(error)
}
}
startAccessingSecurityScopedResource()を呼び出さないと、ファイルの書き込みができないので注意。
Error Domain=NSCocoaErrorDomain Code=513 "You don’t have permission to save the file “hello.txt” in the folder “com~apple~CloudDocs”."
参考