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.
答案 0 :(得分:1)
我遇到了与“persistentStoreForURL”完全相同的问题。事实证明我所寻找的东西会像“persistenStoreWITHUrl”。我错误地认为它实际上会加载商店但事实证明它并没有。当商店已经加载到协调器中时,此功能有效。我意识到你刚才问过这个问题,但我会留下这个,以防其他人遇到同样的问题。因此,更改代码将使其按预期工作:
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)
}