icloud documents tutorial swift code example
Example: get icloud doc swift
class CloudDataManager {
static let sharedInstance = CloudDataManager()
struct DocumentsDirectory {
static let localDocumentsURL: NSURL? = NSFileManager.defaultManager().URLsForDirectory(NSSearchPathDirectory.DocumentDirectory, inDomains: .UserDomainMask).last! as NSURL
static let iCloudDocumentsURL: NSURL? = NSFileManager.defaultManager().URLForUbiquityContainerIdentifier(nil)?.URLByAppendingPathComponent("Documents")
}
func getDocumentDiretoryURL() -> NSURL {
print(DocumentsDirectory.iCloudDocumentsURL)
print(DocumentsDirectory.localDocumentsURL)
if userDefault.boolForKey("useCloud") && isCloudEnabled() {
return DocumentsDirectory.iCloudDocumentsURL!
} else {
return DocumentsDirectory.localDocumentsURL!
}
}
func isCloudEnabled() -> Bool {
if DocumentsDirectory.iCloudDocumentsURL != nil { return true }
else { return false }
}
func deleteFilesInDirectory(url: NSURL?) {
let fileManager = NSFileManager.defaultManager()
let enumerator = fileManager.enumeratorAtPath(url!.path!)
while let file = enumerator?.nextObject() as? String {
do {
try fileManager.removeItemAtURL(url!.URLByAppendingPathComponent(file))
print("Files deleted")
} catch let error as NSError {
print("Failed deleting files : \(error)")
}
}
}
func moveFileToCloud() {
if isCloudEnabled() {
deleteFilesInDirectory(DocumentsDirectory.iCloudDocumentsURL!)
let fileManager = NSFileManager.defaultManager()
let enumerator = fileManager.enumeratorAtPath(DocumentsDirectory.localDocumentsURL!.path!)
while let file = enumerator?.nextObject() as? String {
do {
try fileManager.setUbiquitous(true,
itemAtURL: DocumentsDirectory.localDocumentsURL!.URLByAppendingPathComponent(file),
destinationURL: DocumentsDirectory.iCloudDocumentsURL!.URLByAppendingPathComponent(file))
print("Moved to iCloud")
} catch let error as NSError {
print("Failed to move file to Cloud : \(error)")
}
}
}
}
func moveFileToLocal() {
if isCloudEnabled() {
deleteFilesInDirectory(DocumentsDirectory.localDocumentsURL!)
let fileManager = NSFileManager.defaultManager()
let enumerator = fileManager.enumeratorAtPath(DocumentsDirectory.iCloudDocumentsURL!.path!)
while let file = enumerator?.nextObject() as? String {
do {
try fileManager.setUbiquitous(false,
itemAtURL: DocumentsDirectory.iCloudDocumentsURL!.URLByAppendingPathComponent(file),
destinationURL: DocumentsDirectory.localDocumentsURL!.URLByAppendingPathComponent(file))
print("Moved to local dir")
} catch let error as NSError {
print("Failed to move file to local dir : \(error)")
}
}
}
}
}