1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

iOS/macCatalystアプリで、指定されたフォルダの中にファイルを書き出す

1
Posted at

概要

  • iOS 13以降では、UIDocumentPickerViewControllerdocumentTypeskUTTypeFolderを指定すると、フォルダを選択させることが可能になっている。
  • 選択されたフォルダに対してstartAccessSecurityScopedResourceを呼び出すと、そのフォルダの下にファイルを書き込むことができる。

Permissionの設定

App Sandboxで「User Selected File」を「Read/Write」に設定する。

UIDocumentPickerViewControllerで書き込み先フォルダを選ぶ

iOS 13以降ではUIDocumentPickerViewControllerdocumentTypeskUTTypeFolderを指定することで、フォルダの選択が可能となっている。

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”."

参考

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?