7

我正在开发一个带有 widgetKit 扩展的应用程序,我想在小部件上显示用户创建的数据。widgetKit 如何读取应用创建的文件?

4

2 回答 2

4

您应该使用App Groups Capability在目标之间共享数据。

这是RayWanderlich的一个很好的教程

于 2020-09-09T16:58:03.223 回答
4

为了读取iOS widgetKit创建的文件,你需要在共享容器中创建文件

let url = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "yourapp.contents")?.appendingPathComponent("hello")
let data = Data("test read".utf8)
try! data.write(to: url!)

并且可以读取 Widget 类中的数据

@main
struct StuffManagerWidget: Widget {
    let kind: String = "TestWidget"

    var body: some WidgetConfiguration {
        IntentConfiguration(kind: kind, intent: TestIntent.self, provider: Provider()){ entry in
            WidgetEntryView(entry: entry, string: string)
        }
        .configurationDisplayName("My Widget")
        .description("This is an example widget.")
    }
    
    var string: String = {
        let url = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "yourapp.contents")?.appendingPathComponent("hello")
        let data = try! Data(contentsOf: url!)
        let string = String(data: data, encoding: .utf8)!
        return string
    }()
}
于 2020-09-09T17:06:14.940 回答