user2698617 user2698617 - 1 month ago 19
Swift Question

iCloud files not visible after app reinstall swift

I'm storing files in iCloud as a means of backup. Uploading and downloading files seems to work fine, but if I delete the app on a device and re-install the app on that same device, I no longer see the files that were uploaded to iCloud (even from that device just before deleting the app). The ubiquityIdentityToken is the same from all installs. I'm not trying to sync among devices, just store and retrieve. I can see the files in \settings\icloud\manage storage\ but not by running this code:

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


Any guidance would be appreciated. Swift 3, iOS 10, Xcode 8

Answer

Hard to believe no one else has had this issue. Again, this is for simple file storage and retrieval, not syncing dynamically among devices.

The gist of the issue is that iCloud does not automatically sync cloud files down to a new device. Your code must do that. So if you remove an app from a device (but not from iCloud) and reinstall that same app, the app will not see prior iCloud files. You can add new ones and see them with the code above, but you are really just seeing the local ubiquitous container copy. To see previous items you need to perform a metadataQuery on iCloud, parse the filenames of the files of interest from the metadataQuery results and then run startDownloadingUbiquitousItem(at:) on each file. For example, make an array of files in iCloud from the metadataQuery results and put this do-catch in a for-in loop.

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