如何读取由 iOS WidgetKit 应用程序创建的文件?

Col*_*ang 6 ios swift widgetkit

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

小智 5

您应该使用应用程序组功能在目标之间共享数据。

这是RayWanderlich 的一个很好的教程


Col*_*ang 4

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

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

并且可以读取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
    }()
}
Run Code Online (Sandbox Code Playgroud)