swift 将文件从应用程序移动到手机文档文件夹

5w9g7ksd  于 2022-12-10  发布在  Swift
关注(0)|答案(2)|浏览(312)

因此,在我的应用程序中,我创建了一个Test.JSON文件,希望用户能够将其移动到应用程序之外的文档目录中。我知道我必须使用UIDocumentPickerViewController来完成此操作,但还没有找到任何方法来继续。我创建了Test.JSON文件,并可以通过变量data来使用它。
下面的代码可以打开UIDocumentPickerViewController

let documentPicker =
UIDocumentPickerViewController(forExporting: [.documentsDirectory])
        
documentPicker.delegate = self

// Set the initial directory.
documentPicker.directoryURL = .documentsDirectory

// Present the document picker.
present(documentPicker, animated: true, completion: nil)

如何将数据文件附加到UIDocumentPickerViewController,以便将其放置在documents目录中?

uoifb46i

uoifb46i1#

如果您已经有文件的URL,请以文件URL取代'newFile'。'vc'是目前的ViewController
请注意,asCopy = false将移动文档,asCopy = true将复制文档。当asCopy = false时,似乎有bug in iOS 16+禁用了“移动”按钮。错误在后续版本FB11627056中得到修复

//Present Document Picker
let controller = UIDocumentPickerViewController(forExporting: [newFile], asCopy: false)
vc.present(controller, animated: true) {
    //this will be called as soon as the picker is launched NOT after save
}
jjhzyzn0

jjhzyzn02#

你有没有按照苹果提供的here的说明去做?我在这里总结一下重要的部分:
用户点击“完成”后,系统将调用代理的documentPicker(_:didPickDocumentsAt:)方法,并为用户的选定目录传递一组安全范围的URL ....当用户在文档选取器中选择一个目录时,系统将授予您的应用访问该目录及其所有内容的权限。
所以首先,你需要实现委托方法,这样你就知道用户选择了什么。具体来说,documentPicker(_:didPickDocumentsAt:)是很重要的一个,尽管你也会想监听“cancel”。然后你需要访问这个作用域资源并写入它。
下面是我从上面链接的文档中截取的一个例子。这个例子只从目录中 * 读取 *,但是你也可以用同样的方式写入它。

func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentAt url: URL) {
    // Start accessing a security-scoped resource.
    guard url.startAccessingSecurityScopedResource() else {
        // Handle the failure here.
        return
    }

    // Make sure you release the security-scoped resource when you finish.
    defer { url.stopAccessingSecurityScopedResource() }

    // Use file coordination for reading and writing any of the URL’s content.
    var error: NSError? = nil
    NSFileCoordinator().coordinate(readingItemAt: url, error: &error) { (url) in
            
        let keys : [URLResourceKey] = [.nameKey, .isDirectoryKey]
            
        // Get an enumerator for the directory's content.
        guard let fileList =
            FileManager.default.enumerator(at: url, includingPropertiesForKeys: keys) else {
            Swift.debugPrint("*** Unable to access the contents of \(url.path) ***\n")
            return
        }
            
        for case let file as URL in fileList {
            // Start accessing the content's security-scoped URL.
            guard url.startAccessingSecurityScopedResource() else {
                // Handle the failure here.
                continue
            }

            // Do something with the file here.
            Swift.debugPrint("chosen file: \(file.lastPathComponent)")
                
            // Make sure you release the security-scoped resource when you finish.
            url.stopAccessingSecurityScopedResource()
        }
    }
}

相关问题