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

问题描述

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

解决方法

您应该使用应用组功能在目标之间共享数据。

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类中读取数据

@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
    }()
}