我在应用程序中使用iCloud Drive时遇到了困难。我无法在iCloud Drive中创建应用程序的文件夹。
以某种方式,昨天,我设法创建了该文件夹并在其中保存了项目,但是今天,在运行代码之后,该文件夹消失了,无法再保存文件。
这是我昨天成功运行并投入使用的示例代码:
let str = "ivan cantarino"
guard let iCloudPath = FileManager.default.url(forUbiquityContainerIdentifier: nil)?.appendingPathComponent("Documents") else {
print("Failed to get iCloud path")
return
}
print("icloud path:", iCloudPath.absoluteString)
// prints: icloud path: file:///private/var/mobile/Library/Mobile%20Documents/iCloud~com~ivancantarino~Cozynote/Documents
let lastPath = iCloudPath.appendingPathComponent("iCloudDrive.txt")
// writes a file to the directory
do {
try str.write(to: lastPath, atomically: true, encoding: .utf8)
print("success")
} catch {
print("failed to write with error:", error.localizedDescription)
// prints: failed to write with error: The file “iCloudDrive.txt” couldn’t be saved in the folder “Documents”.
}
这是我的info.plist iCloud信息:
<key>NSUbiquitousContainers</key>
<dict>
<key>iCloud.com.ivancantarino.Cozynote</key>
<dict>
<key>NSUbiquitousContainerIsDocumentScopePublic</key>
<true/>
<key>NSUbiquitousContainerName</key>
<string>Cozynote</string>
<key>NSUbiquitousContainerSupportedFolderLevels</key>
<string>Any</string>
</dict>
</dict>
这里是印刷品,表明我使用的是正确的容器:
我更改了应用程序的版本和内部版本号,重新安装了该应用程序,但是以某种方式无法写入该路径。它继续打印错误。
有人可以在这里发现我做错了什么吗?
我开发的应用程序严重依赖iCloud驱动器,最糟糕的是,难以调试无法预测且记录薄弱的东西。
因此,我可以给您几个选择,尝试一下是否有帮助。创建UIDocument
SubClass可能对您有很大帮助,其中之一可以与iCloud Drive很好地交流。
class TextDoc:UIDocument{
var data:String?
override func contents(forType typeName: String) throws -> Any {
return data?.data(using: .utf8) ?? Data()
}
override func load(fromContents contents: Any, ofType typeName: String?) throws {
if let userContent = contents as? Data {
data = String(data: userContent, encoding: .utf8)
}
}
}
let folder = FileManager.default.url(forUbiquityContainerIdentifier: nil)?.appendingPathComponent("Folder")
try? FileManager.default.createDirectory(atPath: folder?.path ?? "", withIntermediateDirectories: true, attributes: nil)
let fileURL = folder?.appendingPathComponent("iCloudDrive.txt")
let uiDoc = TextDoc(fileURL: fileURL!)
uidoc.save(to: url, for: .forOverwriting) { (success) in
print("save was \(success)")
}
如果保存成功,则可以使用open(completionHandler: <#T##((Bool) -> Void)?##((Bool) -> Void)?##(Bool) -> Void#>)
打开它