ios - 将 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>
然后,我将以下代码添加到我的 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
.
别人得到这个了吗?和/或有人知道如何解决这个问题吗?
谢谢!
我还更改了我的应用程序的构建/版本号,但没有任何结果
解决方案
您应该将文件复制到 iCloud 容器,您只将其写入应用程序沙箱。
首先,Documents
在您的 iCloud 容器上创建文件夹 - 如果您将文件存储在其他文件夹中,您在另一台设备上的应用程序将看到该文件夹,但它不会出现在文件应用程序中。
然后将您的 file.txt 复制到Documents
iCloud 容器上的文件夹中。
推荐阅读
- javascript - 如何触发其他网站的按钮
- javascript - 有没有办法迭代 Array() 将字符串键作为 Javascript 中的索引
- c# - 无法加载文件或程序集'Newtonsoft.Json,版本 = 12.0.0.0?
- nginx - nginx在处理错误时无法使用proxy_pass
- ajax - 为什么来自控制器的查询不显示在 Laravel 中使用 ajax 的表中?
- c# - Roslyn (C#) 无法重命名列表元素的字段
- java - 只有在 OkHttp 中不为空时才添加表单字段
- compiler-errors - 带有生命周期符号的奇怪编译错误:“预期的`:`,发现`>`”
- linux - 无法在 docker 容器上运行 dmidecode
- kubernetes - 从外部 GCP 访问内部 loadBalancer (dask-scheduler)