简体   繁体   English

切换 iCloud 同步 iOS15 / SwiftUI

[英]Toggle iCloud Sync iOS15 / SwiftUI

I have recently added iCloud into my iOS15 / SwiftUI App and wanted to implement an on/off toggle for it.我最近将 iCloud 添加到我的 iOS15 / SwiftUI 应用程序中,并希望为其实现开/关切换。 I have already researched all forum posts and the best solution I came up with is:我已经研究了所有论坛帖子,我想出的最佳解决方案是:

struct PersistenceController {
...
init(inMemory: Bool = false) {
    container = NSPersistentCloudKitContainer(name: "myAppName")
    
    if !iCloudSync {
        let description = container.persistentStoreDescriptions.first
        description?.cloudKitContainerOptions = nil
        description?.setOption(true as NSNumber,
                               forKey: NSPersistentHistoryTrackingKey)
...
    }
}

The problem with this is that it doesn't work during runtime.问题在于它在运行时不起作用。 The user has to close and re-open the app.用户必须关闭并重新打开应用程序。

I already tried to add an onChange modifier including the code snippet to the root view but this doesn't do the trick.我已经尝试在根视图中添加一个包含代码片段的 onChange 修饰符,但这并不能解决问题。

Is there a way to toggle iCloud Sync during runtime?有没有办法在运行时切换 iCloud 同步?

Of course it will not work because you initialized PersistenceController .当然它不会工作,因为你初始化了PersistenceController What you can do is create a function in PersistenceController like so:您可以做的是在PersistenceController中创建一个 function ,如下所示:

func toggleCloud() {
    container = NSPersistentCloudKitContainer(name: "myAppName")
    if !iCloudSync {
        let description = container.persistentStoreDescriptions.first
        description?.cloudKitContainerOptions = nil
        description?.setOption(true as NSNumber, forKey: NSPersistentHistoryTrackingKey)
        ...
    }
}

And call it when the toggle changes.并在切换更改时调用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM