首页 > 解决方案 > 将 iCloud Drive 文件管理器添加到应用程序 - iOS 13

问题描述

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

首先,我添加NSUbiquitousContainers到 info.plist

<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 功能添加到我的应用程序中: 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.

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

谢谢!

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

标签: iosswiftxcodeicloud

解决方案


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

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

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


推荐阅读