I am developing an app with widgetKit extension, and I want to show data created by the user on the widget. How can the widgetKit read files created by the app?
You should use App Groups Capability to share data between your targets.
Here is a good tutorial by RayWanderlich
In order to read files created by the iOS widgetKit, you need to create files in the shared container
let url = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "yourapp.contents")?.appendingPathComponent("hello")
let data = Data("test read".utf8)
try! data.write(to: url!)
And you can read the data in the Widget class
@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
}()
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With