Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read files created by the app by iOS WidgetKit?

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?

like image 693
Collin Zhang Avatar asked Sep 09 '20 16:09

Collin Zhang


2 Answers

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

Here is a good tutorial by RayWanderlich

like image 122
Daniel E. Salinas Avatar answered Nov 14 '22 20:11

Daniel E. Salinas


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
    }()
}
like image 41
Collin Zhang Avatar answered Nov 14 '22 22:11

Collin Zhang