0

I have a struct array, for example:

  struct Note {

   let id: Int
   let text: String
   let timestamp: Int64
   
}

I want to send to the widget. As I searched, I can send an array through AppGroup with userDefaults, I need some tricks to send the struct array with it, but I need the its model on the widget side as well, which I don't have access to it.

Now, I want to know what is the best way to do that? convert it to Json and send via FileManager and encode it again on the widget side? Or use CoreData? or any other suggestion?

Thank you so much for your help in advance.

Robert kont
  • 165
  • 1
  • 8

1 Answers1

0

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
}
Ray Xu
  • 130
  • 5