如何读取iOS WidgetKit应用创建的文件? [英] How to read files created by the app by iOS WidgetKit?

查看:91
本文介绍了如何读取iOS WidgetKit应用创建的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个带有widgetKit扩展名的应用程序,并且我想在小部件上显示用户创建的数据. 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?

推荐答案

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

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!)

您可以在Widget类中读取数据

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

这篇关于如何读取iOS WidgetKit应用创建的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆