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

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

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

您应该使用App Groups Capability在您的目标之间共享数据。

这是 RayWanderlich

的好作品 tutorial

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

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

并且可以读取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
    }()
}