1

I'd like to be able to persist my data model for offline usage. I am using a struct that looks like:

public struct Response: Codable {
    var id: String
    var title: String
    var message: String
    var user: User
}

Is it possible to store the entire Response object into UserDefaults? I want to display this data even when offline. I am using SwiftUI with a State var called responseObject which will react to changes on the UI. I created a List and looping through the items from the responseObject:

 @State private var responseObject = [Response]()

    List(self.responseObject, id: \.id) { item in
        HStack {
            Spacer()
            VStack {
                URLImage(url: item.message)
                    .frame(width: 240, height: 240)
                    .aspectRatio(contentMode: .fit)
                    .cornerRadius(10)
                Text(item.title)
                    .font(.headline)
                    .multilineTextAlignment(.center)
                    .foregroundColor(Color(UIColor.white))
                    .padding(.horizontal, 8)
                Text(item.user.name)
                    .font(.subheadline)
                    .multilineTextAlignment(.center)
                    .foregroundColor(Color(UIColor.white))
                    .padding(.horizontal, 8)
            }
            Spacer()
        }
    }

I am trying to store the decodedResponse from json into a UserDefault like:

UserDefaults.standard.set(decodedResponse.stories, forKey: "responseData")

and then if offline, update the responseObject state var like

self.responseObject = defaults.object(forKey: "responseData") as! [Response]

It's crashing when offline. Think I might be using the defaults incorrectly. Want to avoid something too complex like CoreData.....

Or is there a more "SwiftUI" way to achieve this?

Any info would be really appreciated! Thanks!

Reiss Zurbyk
  • 103
  • 7

0 Answers0