除了'UserDefaults`之外还有其他任何方法可以在iOS中使用`Today Widget Extension`和主`Container Application`之间共享数据

时间:2018-01-05 07:31:27

标签: ios swift core-data

我的意思是我想知道是否可以使用共享公共资源的CoreData

2 个答案:

答案 0 :(得分:1)

您可以选择在主应用和小部件之间共享SQLite和用户默认值。

如果您希望在主应用程序和窗口小部件之间共享SQLite,请按照步骤进行操作。

  1. 创建一个应用组。 点击主项目 - >能力 - >应用程序组 - >创建一个组。。例如:group.com.appname.appgroup

  2. 创建持久协调器时,在应用程序组中创建一个SQLite文件并提供路径。

    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
    let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
    let directory = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.com.appname.appgroup")!
    let url = directory.appendingPathComponent("somename.sqlite")
    var failureReason = "There was an error creating or loading the application's saved data."
    do {
        try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: [NSMigratePersistentStoresAutomaticallyOption:true,NSInferMappingModelAutomaticallyOption:true])
    } catch {
        // Report any error we got.
        var dict = [String: AnyObject]()
        dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" as AnyObject?
        dict[NSLocalizedFailureReasonErrorKey] = failureReason as AnyObject?
        dict[NSUnderlyingErrorKey] = error as NSError
        let wrappedError = 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 \(wrappedError), \(wrappedError.userInfo)")
        abort()
    }
        return coordinator}()
    
  3. 您可以像在主应用中使用的方式一样访问小部件中的核心数据。

  4. 如果您想使用用户默认值,请按照以下步骤操作。

    1. 创建用户deafult对象。
        

      var userDefaults =   UserDefaults(suiteName: “group.com.appname.appgroup”)!

    2. 使用此对象设置和检索值。

答案 1 :(得分:1)

您可以通过钥匙串共享和应用程序组在扩展程序和主机应用程序之间共享数据(需要在目标功能中进行配置)。

KeychainAccess共享钥匙串的示例:

import KeychainAccess

let sharedKeychain = Keychain(service: "com.company.App.shared" , accessGroup: "TeamId.App")
sharedKeychain?["username"] = "Test"

用户默认值示例:

var userDefaults = UserDefaults(suiteName: "group.com.company.App")!

App Group中的数据示例:

let fileUrl = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.com.company.App")!

要通过CoreData共享数据,只需将数据库文件放入App Group存储区。

CoreStore示例:

import CoreStore

let dataStack: DataStack = {
    let dataStack = DataStack(xcodeModelName: "App")
    let storagePathUrl = fileUrl.appendingPathComponent("App.sqlite")
    do {
        try dataStack.addStorageAndWait(SQLiteStore(fileURL: storagePathUrl, configuration: "Default", localStorageOptions: .
            recreateStoreOnModelMismatch))
    } catch let error {
        print("Cannot set up database storage: \(error)")
    }
    return dataStack
}()