简体   繁体   English

使用 Swift 和 iOS 保存文件

[英]Save file using Swift and iOS

I have an iOS app and I need to be able to pick a file on my iCloud Drive, modify the file, and save the modified file with a new extension.我有一个 iOS 应用程序,我需要能够在我的 iCloud Drive 上选择一个文件,修改该文件,并使用新的扩展名保存修改后的文件。 I've tried lots of things but I still can't write the new file.我已经尝试了很多东西,但我仍然无法编写新文件。 Here is my latest code:这是我的最新代码:

documentPickerViewController = DocumentPickerViewController(documentTypes: ["public.item"], in: .open)  
func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {  
    let fileURL = urls[0]  
    do {  
        // Read the file       
        _ = fileURL.startAccessingSecurityScopedResource()  
        let fileData = try Data(contentsOf: fileURL, options: .uncached)  
        fileURL.stopAccessingSecurityScopedResource()  

        // write the file  
        let fileCopyURL = fileURL.appendingPathExtension("copy")  
        _ = fileCopyURL.startAccessingSecurityScopedResource()  
        try fileData.write(to: fileCopyURL)  
        fileCopyURL.stopAccessingSecurityScopedResource()  
    }  
    catch {  
        print(error.localizedDescription)  
    }  
}  

When I pick a file on my iCloud Drive I get the following error:当我在 iCloud Drive 上选择文件时,出现以下错误:

You don't have permission to save the file “TestFile.txt.copy” in the folder “Test Files”.您无权将“TestFile.txt.copy”文件保存在“Test Files”文件夹中。

How can a save the modified file?如何保存修改后的文件?

First, I think you should make sure that you have the correct entitlements/permissions to write to iCloud Drive:首先,我认为您应该确保您拥有正确的权利/权限来写入 iCloud Drive: Xcode 截图

If this still doesn't work, try updating the CFBundleVersion or Build Number of your app and make sure that your Bundle Identifier (in the first section of Signing & Capabilities ) is correctly registered on your Apple Developer account.如果这仍然不起作用,请尝试更新您的应用程序的CFBundleVersion或 Build Number,并确保您的 Bundle Identifier(在Signing & Capabilities的第一部分中)在您的 Apple Developer 帐户中正确注册。

According to your code, what you're trying to accomplish is feasible but the issue comes from elsewhere.根据您的代码,您要完成的工作是可行的,但问题来自其他地方。

Let me know if you have an issue following these steps.如果您在执行这些步骤时遇到问题,请告诉我。 Good Luck!祝你好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM