使用iCloud文档存储的最佳方法 [英] Best way to use iCloud Documents Storage

查看:140
本文介绍了使用iCloud文档存储的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我当前在我的iOS应用中使用本地存储.用户数据存储在文档目录中,现在我打算改为使用iCloud文档存储.

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.

这是我打算做的事情:

  1. 检查iCloud在设备上是否可用

  1. Checking if iCloud is available on the device

如果是,请使用URLForUbiquityContainerIdentifier获取iCloud容器URL

If yes, use URLForUbiquityContainerIdentifier to get the iCloud container URL

将新文件和文档保存到该新URL

Save new files and documents to this new URL

为此,我正在使用此代码,该代码将返回文档文件夹的URL(iCloud或本地)

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
        }
    }
}

这是最佳做法吗? 我担心如果一天没有iCloud会出现问题,因此将使用本地目录而不是云容器,并且该目录将为空. 谢谢.

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.

推荐答案

感谢上面的评论,并通过进一步的阅读,我找到了解决问题的方法.

Thanks to the comment above and with further readings, I've find a way to solve my problem.

这是我决定这样做的方式:

  • 默认情况下,iCloud将被激活
  • 用户可以使用UISwitch在应用程序中禁用/启用iCloud
  • 当用户禁用iCloud时,所有iCloud文件都将在本地传输
  • 当用户启用iCloud时,所有本地文件都将在iCloud Ubiquity容器中传输
  • 没有数据合并

不会丢失此数据.

我想几乎每个人都将使用iCloud,并且一切都将透明而无痛.无论如何,我同步的文件都很小,因此应该可以正常工作(到目前为止).

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).

我有5种简单方法:

  1. 检查iCloud是否可用的方法
  2. 根据用户选择(iCloud或本地)返回文档URL的方法
  3. 删除目录中所有文件(应用使用的文件)的方法
  4. 将文件从本地目录移动到iCloud容器的方法
  5. 将fies从iCloud容器移动到本地目录的方法

这是我的班上处理这个问题的人

class CloudDataManager {

static let sharedInstance = CloudDataManager() // Singleton

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")

}


// Return the Document directory (Cloud OR Local)
// To do in a background thread

func getDocumentDiretoryURL() -> NSURL {
    print(DocumentsDirectory.iCloudDocumentsURL)
    print(DocumentsDirectory.localDocumentsURL)
    if userDefault.boolForKey("useCloud") && isCloudEnabled()  {
        return DocumentsDirectory.iCloudDocumentsURL!
    } else {
        return DocumentsDirectory.localDocumentsURL!
    }
}

// Return true if iCloud is enabled

func isCloudEnabled() -> Bool {
    if DocumentsDirectory.iCloudDocumentsURL != nil { return true }
    else { return false }
}

// Delete All files at URL

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)")
        }
    }
}

// Move local files to iCloud
// iCloud will be cleared before any operation
// No data merging

func moveFileToCloud() {
    if isCloudEnabled() {
        deleteFilesInDirectory(DocumentsDirectory.iCloudDocumentsURL!) // Clear destination
        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)")
            }
        }
    }
}

// Move iCloud files to local directory
// Local dir will be cleared
// No data merging

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)")
            }
        }
    }
}



}

这篇关于使用iCloud文档存储的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆