【问题标题】:Saving a file to icloud drive将文件保存到 icloud 驱动器
【发布时间】:2021-03-18 07:04:59
【问题描述】:

我正在尝试将文件保存到 icloud 驱动器。我会选择简单的版本,我不让用户选择保存文件的位置,我只是将它保存在 icloud 驱动器的根目录中。这是我正在使用的代码:

func exportToFiles() {
    for page in pages {
            let filename = getDocumentsDirectory().appendingPathComponent((page.title ?? "Untitled") + ".png")
        if let image = exportImage(page: page, dpi: 300) {
            if let data = image.pngData() {
                try? data.write(to: filename)
            }
        }
    }
}

func getDocumentsDirectory() -> URL {
    let driveURL = FileManager.default.url(forUbiquityContainerIdentifier: nil)?.appendingPathComponent("Documents")
    return driveURL!
}

我的Info.plist 文件中有这个:

<key>NSUbiquitousContainers</key>
<dict>
        <key>iCloud.com.mysite.myapp</key>
        <dict>
                <key>NSUbiquitousContainerIsDocumentScopePublic</key>
                <true/>
                <key>NSUbiquitousContainerName</key>
                <string>myapp</string>
                <key>NSUbiquitousContainerSupportedFolderLevels</key>
                <string>Any</string>
        </dict>
</dict>

在 UI 中,它看起来很有效,因为在我点击按钮后会有轻微的停顿。但是当我查看我的文件时,那里什么都没有。我做错了什么?

【问题讨论】:

  • 您是否仔细检查了 info.plist 文件中的密钥是否与 iCloud.*bundleID* 匹配,如果您更改了 info.plist,请增加内部版本号
  • 哦,我不知道。我修复了所有这些问题,但它仍然无法正常工作,所以还有其他问题:P 但是谢谢!

标签: ios swift icloud-drive


【解决方案1】:

您必须检查并创建“文档”文件夹,处理错误也是一个好习惯:

if let containerUrl = FileManager.default.url(forUbiquityContainerIdentifier: nil)?.appendingPathComponent("Documents") {
    if !FileManager.default.fileExists(atPath: containerUrl.path, isDirectory: nil) {
        do {
            try FileManager.default.createDirectory(at: containerUrl, withIntermediateDirectories: true, attributes: nil)
        }
        catch {
            print(error.localizedDescription)
        }
    }
    
    let fileUrl = containerUrl.appendingPathComponent("hello.txt")
    do {
        try "Hello iCloud!".write(to: fileUrl, atomically: true, encoding: .utf8)
    }
    catch {
        print(error.localizedDescription)
    }
}

【讨论】:

  • 试过这个解决方案,但第一个 if 语句返回 false...有什么想法吗?
  • @AvivProfesorsky 我也有同样的问题,你找到解决办法了吗?
【解决方案2】:

请仔细检查“签名和功能”选项卡中,您已检查 iCloud 选项卡中的“iCloud 文档”选项。并且还创建了具有完全相同名称的容器 - “myapp”,就像您在 plist 文件中指定的那样。

<key>NSUbiquitousContainerName</key>
<string>myapp</string>

exportImage(page: page, dpi: 300)的返回值是多少? 请确保它正在返回 UIImage 对象。

【讨论】:

    猜你喜欢
    • 2022-10-26
    • 2015-11-24
    • 2015-01-08
    • 1970-01-01
    • 1970-01-01
    • 2014-11-04
    • 1970-01-01
    • 2019-01-11
    • 1970-01-01
    相关资源
    最近更新 更多