8

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?

Collin Zhang
  • 483
  • 5
  • 14
  • 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 Answers2

5

You should use App Groups Capability to share data between your targets.

Here is a good tutorial by RayWanderlich

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
  • 46,897
  • 22
  • 145
  • 209
Collin Zhang
  • 483
  • 5
  • 14
  • 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
  • @CristianMoisei By default, files are created with a 'not available until device is unlocked' flag, and widget code might run in such cases. You might need to modify file's attributes: `FileManager.default.setAttributes([FileAttributeKey.protectionKey: FileProtectionType.none], ofItemAtPath: dataFolderUrl.path)` – Tomáš Kafka Sep 27 '22 at 08:18