我的应用会生成我要复制到用户的iCloud Drive帐户的特定图像文件。
根据我的理解,对setUbiquitous()的简单调用应该触发iCloud在设备之间同步文件,以便用户可以在Mac查找器上显示文件。
我的代码如下:
class func write(image data: Data, to path: String) -> URL? {
var path = "\(path).\(ext)"
let fullPath = getDocumentsDirectory().appendingPathComponent(path)
do {
try data.write(to: fullPath, options: [.atomic])
// Make it ubiquitous
if var ubiquityUrl = FileManager.default.url(forUbiquityContainerIdentifier: nil) {
ubiquityUrl = ubiquityUrl.appendingPathComponent("Documents/\(path)")
setUbiquitous(localUrl: fullPath, ubiquityUrl: ubiquityUrl)
print("Setting ubiquitous at \(ubiquityUrl)")
}
else {
print("Unable to access iCloud Account")
print("Open the Settings app and enter your Apple ID into iCloud settings")
}
return fullPath
}
catch let error {
print("write(image:to:): failed with error \(error) – bad permissions, bad filename, missing permissions, or more likely it can't be converted to the encoding")
return nil
}
}
class func setUbiquitous(localUrl: URL, ubiquityUrl: URL) {
do {
try FileManager.default.setUbiquitous(true, itemAt: localUrl, destinationURL: ubiquityUrl)
} catch let error {
print("*** error: setUbiquitous failed \(error.localizedDescription)")
}
}
不幸的是,到目前为止,我还没有成功实现这一目标。我有这个错误:
Setting ubiquitous at file:///private/var/mobile/Library/Mobile%20Documents/iCloud~com~***~Tree/Documents/3481-4.jpg
*** error: setUbiquitous failed The file “3481-4.jpg” couldn’t be saved in the folder “***Tree” because a file with the same name already exists.
我应该如何更新现有文件?
此外,我在iCloud管理设置应用程序中看不到任何文件,因为我的应用程序未列出(尽管在使用iCloud之前它已在笔中列出)。
旁注:
根据this,我在关键的NSUbiquitousContainers下的plist文件中添加了以下内容,但我不确定它扮演的角色或者它与我对iCloud的使用是否真的相关。
<dict>
<key>com.***.Tree</key>
<dict>
<key>NSUbiquitousContainerIsDocumentScopePublic</key>
<true/>
<key>NSUbiquitousContainerSupportedFolderLevels</key>
<string>Any</string>
<key>NSUbiquitousContainerName</key>
<string>AppleTree</string>
</dict>
</dict>