2016-10-16 63 views
0

我將文件存儲在iCloud中作爲備份的一種手段。上傳和下載文件似乎工作正常,但如果我刪除設備上的應用程序並在同一設備上重新安裝應用程序,我不會再看到上傳到iCloud的文件(甚至在刪除應用程序之前從該設備上傳文件)。 ubiquityIdentityToken在所有安裝中都是相同的。我不想在設備之間同步,只是存儲和檢索。我可以\而不是通過運行此代碼見\設置\ icloud的\管理存儲中的文件:應用程序重新安裝swift後iCloud文件不可見

func createListOfSQLBaseFilesIniCloudDocumentsDirectory() -> [String]{ 

    let iCloudDocumentsURL = FileManager.default.url(forUbiquityContainerIdentifier: nil)?.appendingPathComponent("Documents") 

    var iCloudBackupSQLFiles = [String]() 

    do{ 
     let directoryContents = try FileManager.default.contentsOfDirectory(at: iCloudDocumentsURL!, includingPropertiesForKeys: nil, options: []) 

     for myFile in directoryContents { 
      if myFile.pathExtension == "sqlite" { 

       let fileWithExtension = myFile.lastPathComponent 
       //backupSQLFiles is an array of full file names - including the extension 
       iCloudBackupSQLFiles.append(fileWithExtension) 

      }//if myFile 
     }//for in 

    } catch let error as NSError { 
     print("Unresolved error \(error), \(error.userInfo)") 
    }//do catch 

    return iCloudBackupSQLFiles 

}//createListOfSQLBaseFilesIniCloudDocumentsDirectory 

任何指導,將不勝感激。 Swift 3,iOS 10,Xcode 8

回答

4

很難相信沒有其他人有過這個問題。再次,這是爲了簡單的文件存儲和檢索,而不是在設備之間動態同步。

問題的關鍵在於iCloud不會自動將雲文件同步到新設備。你的代碼必須這樣做。因此,如果您從設備中刪除應用程序(但不是從iCloud)並重新安裝該應用程序,則應用程序將不會看到之前的iCloud文件。您可以添加新的代碼並使用上面的代碼查看它們,但是您實際上只是看到本地無處不在的容器副本。要查看以前的項目,您需要在iCloud上執行metadataQuery,從metadataQuery結果中解析感興趣文件的文件名,然後在每個文件上運行 startDownloadingUbiquitousItem(at :)。例如,從metadataQuery結果中創建一個iCloud中的文件數組,並將此do-catch放在for-in循環中。

let fileManager = FileManager.default 
let iCloudDocumentsURL = FileManager.default.url(forUbiquityContainerIdentifier: nil)?.appendingPathComponent("Documents", isDirectory: true) 
let iCloudDocumentToCheckURL = iCloudDocumentsURL?.appendingPathComponent(whateverFileName, isDirectory: false) 

do { 
    try fileManager.startDownloadingUbiquitousItem(at: iCloudDocumentToCheckURL!) 
    print("tested file: \(whateverFileName)") 

} catch let error as NSError { 
    print("Unresolved error \(error), \(error.userInfo)") 
}//do catch 
相關問題