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?
Asked
Active
Viewed 1,597 times
8
-
This answer might be helpful: [Share data between main App and Widget in SwiftUI for iOS 14](https://stackoverflow.com/questions/63922032/share-data-between-main-app-and-widget-in-swiftui-for-ios-14) – pawello2222 Sep 21 '20 at 22:48
2 Answers
5
You should use App Groups Capability to share data between your targets.
Here is a good tutorial by RayWanderlich
Daniel E. Salinas
- 351
- 3
- 19
4
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
}()
}
pawello2222
- 34,912
- 15
- 99
- 151
Collin Zhang
- 433
- 4
- 13
-
ATTENTION: When you run the app on real device, you have to configure the shared container in TARGET -> Capabilities -> App Group for both the app target and widget target – Collin Zhang Sep 16 '20 at 11:11
-
I get the error: Extra argument 'string' in call when writing this: (entry: entry, string: string) – submariner Oct 16 '20 at 15:57
-
This is great, but do you know if it's possible for the widget to read files created by the application? I am storing data in the ubiquitous container and can't seem to be able to read them from the widget. – CristianMoisei Oct 20 '20 at 18:37