问题描述
struct Note {
let id: Int
let text: String
let timestamp: Int64
}
我想发送到小部件。在搜索时,我可以使用AppGroup
通过userDefaults
发送一个数组,我需要一些技巧来发送struct数组,但是我也需要它在小部件侧的模型,我不知道无法访问它。
现在,我想知道什么是最好的方法?将其转换为Json并通过FileManager
发送,然后再次在小部件侧对其进行编码?还是使用CoreData
?或其他建议?
非常感谢您的提前帮助。
解决方法
假设您已经设置了AppGroup;如果没有,请查看这篇文章Sharing data with a Widget
首先,将您的结构设为Codable
:
struct Note: Codable {
let id: Int
let text: String
let timestamp: Int64
}
您可以将Struct文件放入一个包中,并将其添加为框架,以便可以在主应用程序和小部件中使用它。或者,您可以在主应用程序和小部件扩展名上添加文件目标成员资格。
然后将其转换为JSON
,通过FileManager
写入文件,示例代码:How to read files created by the app by iOS WidgetKit?
//Init your Note array
//Add your code here <-
let encoder = JSONEncoder()
do {
let jsonData = try encoder.encode(/*your note array*/)
// Write to the file system,you can follow the article above or make your own.
// Add your code here <-
WidgetCenter.shared.reloadTimelines(ofKind: "/*Your widget kind*/")
} catch {
Log.error("Save widget error: \(error.localizedDescription)")
}
最后,在小部件时间轴或单独的函数中解码:
if let jsonData = //Read your saved JSON file {
let decoder = JSONDecoder()
do {
let model = try decoder.decode([Note].self,from: jsonData)
// Do whatever you need to do with your model
} catch {
Log.error("Read widget error: \(error.localizedDescription)")
//Should display an error view
}
} else {
//Should display an error view
}