在iOS的SwiftUI中的主应用程序和小部件之间共享数据14 [英] Share data between main App and Widget in SwiftUI for iOS 14
问题描述
@main
struct ClockWidgetExt: Widget {
private let kind: String = "ClockWidgetExt"
public var body: some WidgetConfiguration {
StaticConfiguration(kind: kind, provider: Provider(), placeholder: PlaceholderView()) { entry in
HomeTestView()
}
.configurationDisplayName("My Widget")
.description("This is an example widget.")
}
}
如何从我的主应用程序将数据获取到小部件?
How can I get data from my Main App to the widget?
推荐答案
You can add the AppGroup capability for both your Widget and App (here is a very good explanation how to add it).
代替
UserDefaults.standard
只需为您的AppGroup使用共享的UserDefaults
:
just use the shared UserDefaults
for your AppGroup:
UserDefaults(suiteName: <your_app_group>)
然后,您可以按照此答案中的说明读取/写入数据.
Then you can read/write data like explained in this answer.
使用AppGroup授权,您可以访问共享的文件容器:
With the AppGroup entitlement you get access to the shared File Container:
let containerURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: <your_app_group>)!
并访问如下网址:
let someFileURL = containerURL.appendingPathComponent("SomeFile.txt")
然后,您可以按照此答案中的说明使用共享文件容器:
Then you can use your shared File Container like explained in this answer:
您也可以创建一个共享的CoreData容器:
You can create a shared CoreData container as well:
let storeURL = containerURL.appendingPathComponent("DataModel.sqlite")
let description = NSPersistentStoreDescription(url: storeURL)
let container = NSPersistentContainer(name: "DataModel")
container.persistentStoreDescriptions = [description]
container.loadPersistentStores { ... }
然后,您可以按照此答案中的说明使用共享的CoreData容器:
Then you can use your shared CoreData Container like explained in this answer:
这是一个 GitHub存储库,其中包含包括应用程序组在内的不同窗口小部件示例小部件.
Here is a GitHub repository with different Widget examples including the App Group Widget.
这篇关于在iOS的SwiftUI中的主应用程序和小部件之间共享数据14的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!