Search code examples
jsonswiftstructnsuserdefaults

How I can pass json data with a decodable struct to UserDefaults properly


I'm a student and I am trying to get a Json Data from an Http Server, and after that save it using UserDefaults

I saw some examples and this code I made seemed to make sense even though it did not work

That is my struct I'm using to decode the json Data

struct UserLogged : Decodable {
    var token: String
    var userId: String
}

And this is the code I'm trying to use

guard let baseUrl = URL(string: "http://LOCALHOST:8080/auth/login") else {
        return
    }
    var request = URLRequest(url: baseUrl);
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    request.httpMethod = "POST";
    request.httpBody = jsonData;
    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        if let data = data {
            print(data)
            do {
                let json = try JSONSerialization.jsonObject(with: data, options: [])
                print(json)
                if let user : UserLogged = try JSONDecoder().decode(UserLogged.self, from: data) {
                    UserDefaults.standard.set(user, forKey: "userLogged")
                }
            } catch {
                print(error)
            }
        }
}.resume()

Solution

  • You can parse that json with a decoder easily instead of JSONSerialization. It is better to save the token of user in UserDefaults instead of whole user, with a key that makes sense such as userToken:

    if let data = data {
        print(data)
        let decoder = JSONDecoder()
    
        do {
            let user = try decoder.decode(UserLogged.self, from: data)
            //now you parsed the json and get token and userId
            UserDefaults.standard.set(user.token, forKey: "userToken")
        } catch {
            //Parsing error, couldnt parse user.
        }
    }