首页 > 解决方案 > CoreData+CloudKit 集成问题

问题描述

我正在尝试设置 CoreData+CloudKit 集成。但是我在NSPersistentCloudKitContainer配置后立即收到以下错误。

 CoreData: error: CoreData+CloudKit: -[NSCloudKitMirroringDelegate _performSetupRequest:]_block_invoke(939): <NSCloudKitMirroringDelegate: 0x282d18a90>: Failed to set up CloudKit integration for store: <NSSQLCore: 0x10342fbf0> (URL: file:///var/mobile/Containers/Data/Application/18992BCF-7F0C-4271-B106-947B8F52A723/Library/Application%20Support/App.sqlite)
Error Domain=NSCocoaErrorDomain Code=134060 "A Core Data error occurred." UserInfo={NSLocalizedFailureReason=The mirroring delegate could not initialize because it's store was removed from the coordinator.}

这是持久化容器设置的代码:

self.persistentContainer = NSPersistentCloudKitContainer(name: containerName)
 
let localStorage = NSPersistentStoreDescription(url: storageURL)
let localStorageOptions = NSPersistentCloudKitContainerOptions(containerIdentifier: "iCloud.com.myapp")
localStorageOptions.databaseScope = .private
localStorage.cloudKitContainerOptions = localStorageOptions
persistentContainer.persistentStoreDescriptions = [localStorage]
   
persistentContainer.loadPersistentStores { storeDescription, error in
  if let error = error {
    print(error)
  }
}

另一件要提的是,这storageURL是一个共享的应用程序组文件夹。

不知道这里到底出了什么问题,所以很乐意得到任何帮助!

更新

添加完整的设置代码,并创建存储路径。

  setupPersistentContainer(
    containerName: "Model",
    sharedGroupIdentifier: "group.com.example.group.name",
    cloudKitIdentifier: "iCloud.com.example.icloud.name"
  )

  func setupPersistentContainer(
    containerName: String, 
    sharedGroupIdentifier: String, 
    cloudKitIdentifier: String
  ) {
    persistentContainer = NSPersistentCloudKitContainer(name: containerName)
    
    guard let storageURL = sharedStorageURL(for: sharedGroupIdentifier) else {
      // error
      return
    }
    
    let localStorage = NSPersistentStoreDescription(url: storageURL)
    let localStorageOptions = NSPersistentCloudKitContainerOptions(containerIdentifier: cloudKitIdentifier)
    localStorageOptions.databaseScope = .private
    localStorage.cloudKitContainerOptions = localStorageOptions
    persistentContainer.persistentStoreDescriptions = [localStorage]
    
    persistentContainer.loadPersistentStores { storeDescription, error in
      if let error = error {
        fatalError()
      }
      
      print(storeDescription)
    }
  }
  
  // MARK: - Private
  private func sharedStorageURL(for identifier: String) -> URL? {
    guard let containerURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: identifier) else {
      return nil
    }
    
    return containerURL
      .appendingPathComponent("StorageFolder")
      .appendingPathComponent("Model.sqlite")
  }

标签: iosswiftcore-dataicloudcloudkit

解决方案


推荐阅读