Assume you already set up your AppGroup; if not, check out this article Sharing data with a Widget
First, make your struct Codable
:
struct Note: Codable {
let id: Int
let text: String
let timestamp: Int64
}
You could put your Struct file in a package and add it as your framework so you can use it in both your main app and your widget. Or you can add the file target membership on both your main app and your widget extension.
Then convert it to JSON
, write to the File via FileManager
, sample code: 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)")
}
Lastly, Decode in your widget timeline or a separate function:
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
}