【问题标题】:How to optionally use iCloud with core data?如何选择将 iCloud 与核心数据一起使用?
【发布时间】:2024-04-16 10:10:01
【问题描述】:

我计划制作一个切换按钮,以便用户可以选择是否要与 iCloud 同步本地数据, 为用户提供更多隐私。

但似乎我只能选择使用 iCloud(NSPersistentCloudKit) 或不使用(NSPersistentKit)

我找不到提供禁用功能的 NSPersistentCloudkit,或者 如果数据之前存储在本地设备中,是否可以通过 NSPersistentCloudkit 中的某些设置同步到云端?

还是像 WWDC19 所说的那样,是否需要数千行代码?

【问题讨论】:

    标签: ios core-data swiftui cloudkit


    【解决方案1】:

    我找到了一些答案,还没有自己尝试。 但万一有类似问题的读者急需。

    这似乎提供了整个解决方案(ios13): https://fluffy.es/toggle-icloud-sync-nspersistentcloudkitcontainer/

    另请注意,一旦用户选择不同步,以上删除 iCloud 副本, 而https://developer.apple.com/forums/thread/118924 建议不要这样做。

    【讨论】:

    • 你实现了吗?我问是因为,在你上面提到的文章中,很多读者评论说它对他们不起作用。
    【解决方案2】:

    我自己从未尝试过,但如果您使用自定义设置与标准设置相比,您可能会通过将 CloudKit 商店描述设为可选来实现。

    https://developer.apple.com/documentation/coredata/mirroring_a_core_data_store_with_cloudkit/setting_up_core_data_with_cloudkit

    lazy var persistentContainer: NSPersistentCloudKitContainer = {
        let container = NSPersistentCloudKitContainer(name: "Earthquakes")
    
        // Create a store description for a local store
        let localStoreLocation = URL(fileURLWithPath: "/path/to/local.store")
        let localStoreDescription =
            NSPersistentStoreDescription(url: localStoreLocation)
    localStoreDescription.configuration = "Local"
    
        //Make this section optional
        // Create a store description for a CloudKit-backed local store
        let cloudStoreLocation = URL(fileURLWithPath: "/path/to/cloud.store")
        let cloudStoreDescription =
            NSPersistentStoreDescription(url: cloudStoreLocation)
        cloudStoreDescription.configuration = "Cloud"
    
        //Make this section optional
        // Set the container options on the cloud store
        cloudStoreDescription.cloudKitContainerOptions = 
            NSPersistentCloudKitContainerOptions(
                containerIdentifier: "com.my.container")
    
        // Update the container's list of store descriptions
        container.persistentStoreDescriptions = [
            cloudStoreDescription, //Make this line optional
            localStoreDescription
        ]
    
        // Load both stores
        container.loadPersistentStores { storeDescription, error in
            guard error == nil else {
                fatalError("Could not load persistent stores. \(error!)")
            }
        }
    
        return container
    }()
    

    我自己从来没有做过,我会检查商店对用户改变主意的反应。

    【讨论】:

    • 感谢您的回答!我会调查的!