简体   繁体   中英

Migrate local Core Data Store to iCloud for existing project with Swift

I want to enable iCloud for Core Data for an existing project. The user could use the app from a new iPhone or maybe another with his old data. So I have to do a migration of the probably existing store to the new store in iCloud / ubiquitous container.

I added the iCloud Document Capabilities and I use the default Core Data Stack Template from Apple, when you create a new Swift-project with iOS 8.

Apple Core Data Stack Template:

    lazy var applicationDocumentsDirectory: NSURL = {
    let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
    return urls[urls.count-1] as! NSURL
}()

lazy var managedObjectModel: NSManagedObjectModel = {
    let modelURL = NSBundle.mainBundle().URLForResource("testapp", withExtension: "momd")!
    return NSManagedObjectModel(contentsOfURL: modelURL)!
}()

lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
    var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
    let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("testapp.sqlite")
    var error: NSError? = nil
    var failureReason = "There was an error creating or loading the application's saved data."
    if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil {
        coordinator = nil
        // Report any error we got.
        let dict = NSMutableDictionary()
        dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
        dict[NSLocalizedFailureReasonErrorKey] = failureReason
        dict[NSUnderlyingErrorKey] = error
        error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict as [NSObject : AnyObject])
        NSLog("Unresolved error \(error), \(error!.userInfo)")
        abort()
    }

    return coordinator
}()

lazy var managedObjectContext: NSManagedObjectContext? = {
    let coordinator = self.persistentStoreCoordinator
    if coordinator == nil {
        return nil
    }
    var managedObjectContext = NSManagedObjectContext()
    managedObjectContext.persistentStoreCoordinator = coordinator
    return managedObjectContext
}()

// MARK: - Core Data Saving support

func saveContext () {
    if let moc = self.managedObjectContext {
        var error: NSError? = nil
        if moc.hasChanges && !moc.save(&error) {
            NSLog("Unresolved error \(error), \(error!.userInfo)")
            abort()
        }
    }
}

I read at apple developer about the function migratePersistentStore and here at StackOverflow about the answer Move local Core Data to iCloud , but I don't know how to implement this correct in that template.

From my understanding, I think, I have to check in the lazy var definition of the coordinator, if the url points to an existing store/file. If so, I have to migrate to a new store with the function migratePersistentStore:xmlStore and option NSPersistentStoreUbiquitousContentNameKey.

So I wrote a new persistence coordinator:

Persistence Coordinator with migration

   lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
    var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)

    // create new iCloud-ready-store
    let iCloudStoreUrl = self.applicationDocumentsDirectory.URLByAppendingPathComponent("TestAppiCloud.sqlite")
    var iCloudOptions: [NSObject : AnyObject]? = [
        NSPersistentStoreFileProtectionKey: NSFileProtectionComplete,
        NSMigratePersistentStoresAutomaticallyOption: true,
        NSInferMappingModelAutomaticallyOption: true,
        NSPersistentStoreUbiquitousContentNameKey: "TestAppiCloudStore"
    ]

    var error: NSError? = nil
    var failureReason = "There was an error creating or loading the application's saved data."

    if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: iCloudStoreUrl, options: iCloudOptions, error: &error) == nil {
        coordinator = nil
        // Report any error we got.
        var dict = [String: AnyObject]()
        dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
        dict[NSLocalizedFailureReasonErrorKey] = failureReason
        dict[NSUnderlyingErrorKey] = error
        error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
        NSLog("Unresolved error \(error), \(error!.userInfo)")
        abort()
    }

    // Possible old store migration

    let existingStoreUrl = self.applicationDocumentsDirectory.URLByAppendingPathComponent("testapp.sqlite")
    let existingStorePath = existingStoreUrl.path

    // check if old store exists, then ...
    if NSFileManager.defaultManager().fileExistsAtPath(existingStorePath!) {
        // ... migrate
        var existingStoreOptions = [NSReadOnlyPersistentStoreOption: true]
        var migrationError: NSError? = nil

        var existingStore = coordinator!.persistentStoreForURL(existingStoreUrl)
        coordinator!.migratePersistentStore(existingStore!, toURL: iCloudStoreUrl, options: existingStoreOptions, withType: NSSQLiteStoreType, error: &migrationError)
    }

    // iCloud Notifications
    let notificationCenter = NSNotificationCenter.defaultCenter()
    notificationCenter.addObserver(self,
        selector: "storeWillChange",
        name: NSPersistentStoreCoordinatorStoresWillChangeNotification,
        object: coordinator!)
    notificationCenter.addObserver(self,
        selector: "storeDidChange",
        name: NSPersistentStoreCoordinatorStoresDidChangeNotification,
        object: coordinator!)
    notificationCenter.addObserver(self,
        selector: "storeDidImportUbiquitousContentChanges",
        name: NSPersistentStoreDidImportUbiquitousContentChangesNotification,
        object: coordinator!)

    return coordinator
    }()

But I'm getting an exception, when the migration starts at coordinator!.migratePersistentStore:

var existingStore = coordinator!.persistentStoreForURL(existingStoreUrl) // nil

but the fileManager says, it exists!

What am I doing wrong? Is the idea correct? Please help.

I ran into the exact same issue with "persistentStoreForURL". It turns out what I was looking for would have been something like "persistenStoreWITHUrl". I assumed incorrectly that it would actually load the store but as it turns out, it does not. This function works when the store is already loaded in the coordinator. I realize you asked this a while ago, but I'm going to leave this here in case anyone else runs into the same issue. Changing the code thusly will get it to work as intended:

    let coordinator = self.persistentStoreCoordinator
    let existingStore = coordinator.persistentStores.first

    var options = Dictionary<NSObject, AnyObject>()
    options[NSPersistentStoreRemoveUbiquitousMetadataOption] = true
    options[NSMigratePersistentStoresAutomaticallyOption] = true
    options[NSInferMappingModelAutomaticallyOption] = true


    do {
         try coordinator?.migratePersistentStore(existingStore!, to: url2, options: [NSMigratePersistentStoresAutomaticallyOption:true, NSInferMappingModelAutomaticallyOption:true], withType: NSSQLiteStoreType)

    }
    catch {

        print(error)

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM