2017-08-27 135 views
5

我的應用程序創建一個pdf文件,我想要保存該pdf文件到iCloud Drive使用swift 3以編程方式。如何使用swift以編程方式將pdf文檔保存到iCloud Drive?

有關示例,此處我使用了一個Text文件來保存在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

有輸出.. !!我有同樣的問題。文件夾正在創建,但文件內部缺失。你能指導我嗎? –

回答

0

假設您的代碼按預期工作,請嘗試在info.plist中更新您的應用程序的版本和內部版本號。 iCloud更改需要更改這些值才能反映出來。

相關問題