Как получить доступ к Core Data/CouldKit через расширение Today (iOS8)

У меня есть приложение, которое использует Core Data со стандартным стеком Apple Core Data в AppDelegate. Я изменил стек, чтобы Core Data был улучшен с помощью CloudKit. Все данные синхронизируются между всеми устройствами. Все идет нормально.

Я хотел бы добавить расширение «Сегодня» в свое приложение, но не знаю, как получить доступ к данным. Я читал о концепции AppGroup, но я также читал, что я не должен/не могу использовать это для доступа к данным из расширения Today. Поэтому я решил, что мне следует использовать CloudKit, поскольку я узнал, что NSManagedObjects преобразуются в CKRecords при загрузке в iCloud.

Как именно я могу получить доступ к данным через iCloud, которые были сохранены Core Data с помощью расширения CloudKit? Где именно эти данные хранятся в iCloud?

Хотя все данные синхронизируются хорошо, когда я проверяю панель управления iCloud, данных не существует. Все статьи SO, которые я читал, похоже, касаются только части моей проблемы.

Вот модифицированный стек Core Data, который я использую в своем приложении:

    // MARK: - Core Data stack

lazy var managedObjectModel: NSManagedObjectModel = {
    // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
    let modelURL = NSBundle.mainBundle().URLForResource("AppName", withExtension: "momd")!
    return NSManagedObjectModel(contentsOfURL: modelURL)!
    }()

lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
    // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
    // Create the coordinator and store
    var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)

    let documentDirectory = NSFileManager.defaultManager().URLsForDirectory(NSSearchPathDirectory.DocumentDirectory, inDomains: NSSearchPathDomainMask.UserDomainMask).last as! NSURL

    let storeUrl = documentDirectory.URLByAppendingPathComponent("AppName.sqlite")

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

    let storeOptions = [NSPersistentStoreUbiquitousContentNameKey:"ItemsCloudStore"]

    let url = storeUrl

    if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: storeOptions, 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)
        // Replace this with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
        NSLog("Unresolved error \(error), \(error!.userInfo)")
        abort()
    }

    return coordinator
    }()

lazy var managedObjectContext: NSManagedObjectContext? = {
    // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
    let coordinator = self.persistentStoreCoordinator
    if coordinator == nil {
        return nil
    }


            var managedObjectContext = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.MainQueueConcurrencyType)

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

            println("Unresolved error \(error), \(error!.userInfo)")
            abort()

        } else {

            println("Context was updated")
        }
    }
}

person DoertyDoerk    schedule 16.08.2015    source источник
comment
Вы пытались получить доступ к данным из расширения?   -  person Simon    schedule 17.08.2015
comment
Да. Однако, когда я использую AppGroups, чтобы получить доступ из приложения и расширения, я теряю функциональность iCloud. Мне не удалось получить доступ к данным из расширения с помощью CloudKit и приведенного выше кода. Прямо сейчас я нахожусь в процессе переноса всего материала Core Data в фреймворк. Не уверен, действительно ли это тот подход, который я должен использовать, или у него вообще есть шанс оказаться рабочим.   -  person DoertyDoerk    schedule 17.08.2015


Ответы (1)


После некоторых исследований кажется, что это нерешенная проблема Apple. Core Data и iCloud не работают вместе с Extensions. Ознакомьтесь с этой статьей:

https://devforums.apple.com/message/1050891#1050891

Немного облом. Пусть надеются, что исправят хотя бы в iOS9.

person DoertyDoerk    schedule 11.09.2015
comment
К сожалению, эта ссылка, кажется, больше не работает. - person koen; 30.10.2015