【问题标题】:How do I permanently save a file to iCloud using FileManager using Swift?如何使用 Swift 使用 FileManager 将文件永久保存到 iCloud?
【发布时间】:2018-12-29 21:02:34
【问题描述】:

当我将文件保存到 iCloud 时,当应用关闭时,该文件不再存在。

这是我在应用关闭之前的代码,打印结果在打印语句旁边的 cmets 中:

    FileManager.default.createFile(atPath: saveToURL.path, contents: dataImage, attributes: nil)

    print("??? \(saveToURL.path) imagePicker file exists=", FileManager.default.fileExists(atPath: saveToURL.path)) // ??? /private/var/mobile/Library/Mobile Documents/iCloud~us~gnolaum~TrialVisionBoard/12BF0AB3-C0EB-4D13-A37E-7853839225BD.jpg cellForRowAt file exists= false

请注意,当代码在文件创建后检查文件是否存在时,它会检查出 true。

以下是应用重新启动后的代码:

     print("??? \(mediaURL.path) cellForRowAt file exists=", FileManager.default.fileExists(atPath: mediaURL.path)) // ??? /private/var/mobile/Library/Mobile Documents/iCloud~us~gnolaum~TrialVisionBoard/12BF0AB3-C0EB-4D13-A37E-7853839225BD.jpg cellForRowAt file exists= false

注意url路径与应用关闭前的路径相同,但应用重启后的文件不存在。

我怀疑我需要为我创建的文件设置正确的属性。有人知道我需要做什么才能让文件保存在 iCloud 中吗?

附加内容:

我注意到在 iPhone 5 Simulator 上运行项目时没有这个问题。当我在我的 iPhone 5 设备上运行项目时会出现问题。

【问题讨论】:

  • 检查这个stackoverflow.com/a/33912666/1644934或者你可以考虑使用CloudKit或第三方库。
  • @Vincent 就像我解释的那样,我保存到了 iCloud。我正在使用 CloudKit。我应该显示以下代码行:“var saveToURL = FileManager.default.url(forUbiquityContainerIdentifier: nil)!”显示 saveToURL 是 iCloud 的 url。
  • @Vincent 顺便说一句,该行代码位于其他代码行之前,并且在您获得原始代码之前还有其他代码行要添加到它以创建一个完整的 url发布。
  • 我对iCloud没有太多经验,只能给你一些建议。如果这里没有好的答案,我建议你查看一些相关开源库的代码。
  • @Vincent 好的。谢谢。我实际上遇到了一些令人困惑的事情。有时我的代码有效。有时它不会,这取决于我使用的模拟器或设备。我不知道是什么因素决定了这些差异。

标签: ios swift icloud nsfilemanager


【解决方案1】:

我完全错过了这个问题。我发现我需要采取一种完全不同的方法来处理 iCloud 存储,正如本文档所指示的那样:

https://developer.apple.com/library/archive/documentation/FileManagement/Conceptual/FileSystemProgrammingGuide/iCloud/iCloud.html#//apple_ref/doc/uid/TP40010672-CH12-SW51

【讨论】:

    猜你喜欢
    • 2018-01-17
    • 2022-10-26
    • 2018-02-04
    • 1970-01-01
    • 1970-01-01
    • 2016-11-09
    • 2013-01-14
    • 1970-01-01
    • 2014-02-20
    相关资源
    最近更新 更多