Essentially, I have correctly parsed my data. However, when I'm trying to access the data. It claims that I'm attempting to insert non-propert list object into a UserDefaults Array. How would I be able to convert this somehow to a property list object? Or how would I be able to store the JSON array as a string?
var status = UserDefaults.standard.array(forKey: "status") ?? []
struct Response: Codable {
let weather: [MyResult]
}
struct MyResult: Codable {
let main: String
}
func getData(from url:String) {
URLSession.shared.dataTask(with: URL(string:url)!, completionHandler: {
data, response, error in
guard let data = data, error == nil else {
print("Something went wrong")
return
}
// have data
var result: Response?
do {
result = try JSONDecoder().decode(Response.self, from: data)
} catch {
print(error.localizedDescription)
}
guard let json = result else {
return
}
print(type(of: json.weather)) // Array
UserDefaults.standard.set(json.weather, forKey: "status") // Here is the error
print(status)
}).resume()
}
EDIT: When I print status, nothing is there.
func getData(from url:String) {
URLSession.shared.dataTask(with: URL(string:url)!, completionHandler: {
data, response, error in
guard let data = data, error == nil else {
print("Something went wrong")
return
}
// have data
var result: Response?
do {
result = try JSONDecoder().decode(Response.self, from: data)
} catch {
print(error.localizedDescription)
}
guard let json = result else {
return
}
print(type(of: json.weather)) // Array
do {
// Store it with
let data = try JSONEncoder().encode(json.weather)
UserDefaults.standard.set(data, forKey: "status")
// Read it
if let data = UserDefaults.standard.data(forKey:"status") {
let res = try JSONDecoder().decode([MyResult].self,from:data)
}
}
catch {
print(error)
}
print(status)
}).resume()
}
MyResult. This is not JSON. You need to encode it back. And never print meaningless literal strings like"Something went wrong"instead of the actualerror. And in aCodablecatch block print alwayserrorrather thanerror.localizedDescription.