I am currently using local storage in my iOS App. The user data is stored in the Document Directory and now I am planning to use iCloud Documents storage instead.
Here is how I intend to do it :
Checking if iCloud is available on the device
If yes, use URLForUbiquityContainerIdentifier to get the iCloud container URL
Save new files and documents to this new URL
For that I am using this code that will return the URL of the document folder (iCloud or local)
class CloudDataManager {
class func getDocumentDiretoryURL() -> NSURL {
let localDocumentsURL = NSFileManager.defaultManager().URLsForDirectory(NSSearchPathDirectory.DocumentDirectory, inDomains: .UserDomainMask).last! as NSURL
let iCloudDocumentsURL = NSFileManager.defaultManager().URLForUbiquityContainerIdentifier(nil)?.URLByAppendingPathComponent("Documents")
if userDefault.boolForKey("useCloud") && iCloudDocumentsURL != nil {
return iCloudDocumentsURL!
} else {
return localDocumentsURL
}
}
}
Is it the best practice? I am worried problems will occur if one day iCloud isn't available so the local directory will be used instead of the cloud container and will be empty. Thank you.
for those who wants to use SWIFT 3: NOTE: Instead of moving the data I just do copy. But the destination path is cleared before copy data there..
Check this link: iCloud basics and code sample
If the information that you are storing are simple, it's better to use NSUserDefaults. You don't want to ask iCloud for basic information.
Thanks to the comment above and with further readings, I've find a way to solve my problem.
Here is how I decided to do it:
Like this data will not be lost.
I guess almost everyone will use iCloud and everything will be transparent and painless. Anyway the files I sync are pretty small so it should work fine (so far it does).
I have 5 simples methods:
Here is my class that handle the issue