【问题标题】:Adding iCloud Drive File Manager to App - iOS 13将 iCloud Drive 文件管理器添加到应用程序 - iOS 13
【发布时间】:2020-05-05 05:46:57
【问题描述】:

我想支持在我的 iOS 应用程序中向 iCloud 添加文件。我希望将这些文件添加到 iCloud Drive 上的文件夹(例如 Numbers 或 Pages 文件夹)。我尝试了我在网上找到的关于这个主题的所有内容,但我没有设法将文件夹添加到 iCloud Drive。

首先,我在 info.plist 中添加了NSUbiquitousContainers

<key>NSUbiquitousContainers</key>
<dict>
    <key>iCloud.com.<xyz>.AppName</key>
    <dict>
        <key>NSUbiquitousContainerIsDocumentScopePublic</key>
        <true/>
        <key>NSUbiquitousContainerName</key>
        <string>App Name</string>
        <key>NSUbiquitousContainerSupportedFolderLevels</key>
        <string>Any</string>
    </dict>
</dict>

在此之后,我将 iCloud 功能添加到我的应用程序中:

然后,我将以下代码添加到我的 ViewController:

if let iCloudDocumentsURL = FileManager.default.url(forUbiquityContainerIdentifier: nil)?.appendingPathComponent("Documents") {
    if (!FileManager.default.fileExists(atPath: iCloudDocumentsURL.path, isDirectory: nil)) {
        do {
            try FileManager.default.createDirectory(at: iCloudDocumentsURL, withIntermediateDirectories: true, attributes: nil)
        } catch {
            print(error.localizedDescription)
        }
    }
}

注意:设置断点后,我发现if (!FileManager.default.fileExists(atPath: iCloudDocumentsURL.path, isDirectory: nil)) { 之后的代码永远不会被调用。我暂时删除了这一行,但这并没有做任何事情

最后,我使用以下代码添加了一个文件:

//Save text file to local directory
let file = "file.txt" //Text file to save to iCloud
let text = "sample text" //Text to write into the file
func saveToDirectory(){
    guard let directory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return }
    let fileURL = directory.appendingPathComponent(file)

    print(directory)
    //Writing
    do {
        try text.write(to: fileURL, atomically: false, encoding: .utf8)
    } catch {
        /* error handling here */
        print("Error in writing")
    }

    //Reading
    do {
        let getText = try String(contentsOf: fileURL, encoding: .utf8)
        print(getText)
    } catch {
        /* error handling here */
        print("Error in reading")
    }
}

我没有看到应用程序的文件夹,或者上述文件出现在我的 iCloud Drive 上。但是当我下载应用程序容器并查看它的内容时,我会看到/AppData/Documents 下列出的文件。

其他人得到了这个吗?和/或有人知道如何解决这个问题吗?

谢谢!

我还更改了我的应用的构建/版本号,但没有任何结果

【问题讨论】:

    标签: ios swift xcode icloud


    【解决方案1】:

    您应该将文件复制到 iCloud 容器,您只是将其写入应用沙箱。

    首先,在您的 iCloud 容器上创建 Documents 文件夹 - 如果您将文件存储在其他文件夹中,您在其他设备上的应用会看到该文件夹​​,但它不会出现在文件应用中。

    然后将您的 file.txt 复制到 iCloud 容器上的 Documents 文件夹中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-01-07
      • 1970-01-01
      • 1970-01-01
      • 2017-02-06
      • 1970-01-01
      • 1970-01-01
      • 2017-10-11
      相关资源
      最近更新 更多