我的应用创建了一个pdf文件,我想使用swift 3 以编程方式将该pdf文档保存到 iCloud Drive 。
对于示例,我在这里使用了一个文本文件来保存在iCloud Drive中。
这是我的代码:
func copyDocumentsToiCloudDrive() {
var error: NSError?
let iCloudDocumentsURL = FileManager.default.url(forUbiquityContainerIdentifier: nil)?.appendingPathComponent("myCloudTest")
do{
//is iCloud working?
if iCloudDocumentsURL != nil {
//Create the Directory if it doesn't exist
if (!FileManager.default.fileExists(atPath: iCloudDocumentsURL!.path, isDirectory: nil)) {
//This gets skipped after initial run saying directory exists, but still don't see it on iCloud
try FileManager.default.createDirectory(at: iCloudDocumentsURL!, withIntermediateDirectories: true, attributes: nil)
}
} else {
print("iCloud is NOT working!")
// return
}
if error != nil {
print("Error creating iCloud DIR")
}
//Set up directorys
let localDocumentsURL = FileManager.default.urls(for: FileManager.SearchPathDirectory.documentDirectory, in: .userDomainMask).last! as NSURL
//Add txt file to my local folder
let myTextString = NSString(string: "HELLO WORLD")
let myLocalFile = localDocumentsURL.appendingPathComponent("myTextFile.txt")
_ = try myTextString.write(to: myLocalFile!, atomically: true, encoding: String.Encoding.utf8.rawValue)
if ((error) != nil){
print("Error saving to local DIR")
}
//If file exists on iCloud remove it
var isDir:ObjCBool = false
if (FileManager.default.fileExists(atPath: iCloudDocumentsURL!.path, isDirectory: &isDir)) {
try FileManager.default.removeItem(at: iCloudDocumentsURL!)
}
//copy from my local to iCloud
if error == nil {
try FileManager.default.copyItem(at: localDocumentsURL as URL, to: iCloudDocumentsURL!)
}
}
catch{
print("Error creating a file")
}
}
此代码正常运行,没有任何错误。但是没有在iCloud Drive中显示已保存的文件。
我引用此link并编写了此代码。
答案 0 :(得分:1)
假设您的代码按预期工作,请尝试在info.plist中更新应用程序的版本和内部版本号。需要更改这些值才能反映iCloud更改。