-1

I have made an API call to log my users in an app. i am using Alamofire and SwiftyJSON. API call works well and I get a JSON file like this one :

{
    "code": 200,
    "message": "OK",
    "data": {
         "user_id": 1,
         "user_email": "test",
         "user_username": "kk1",
    }
}

In order to save the user info in UserDefault, I want to create my User object with this JSON response. Here is the model

class LFUser: NSObject {

    var user_id: Int?
    var user_email: String?
    var user_username: String?

    init(dict: [String: AnyObject]){
        super.init()
        user_id = dict["user_id"] as? Int
        user_email = dict["user_email"] as? String
        user_username = dict["user_username"] as? String
    }
}

Here is the part of the login function when the API call and the objectis created :

func login(userEmail: String, userPassword: String, finished: @escaping(_ status:String,_ data: LFUser?)-> ()) {

            if let value = response.result.value {

            let dict = JSON(value)
            let code = dict["code"].intValue
            let message = dict["message"].stringValue



            if let data = dict["data"].dictionary {

                print(data)
                let user = LFUser(dict: data as [String : AnyObject])
                print(user.user_email)
                finished("Success", user)

        }
    }

The print(data) works well but there is a problem when creating the object and the print(user.user_email) display nil.

Hitesh
  • 896
  • 1
  • 9
  • 22
Florian Ldt
  • 1,125
  • 3
  • 13
  • 31

2 Answers2

0

I would go for Swift 4’s Codable instead:

struct User: Codable {
    let user_id: Int
    let user_email: String
    let user_username: String
}

struct Response: Codable {
    let code: Int
    let message: String
    let data: User
}

Then you can decode the incoming data like that:

let response = try JSONDecoder().decode(Response.self, from: jsonData)

Then, in order to save the value to user defaults, you can use JSONEncoder or PropertyListEncoder to encode the value to Data.

zoul
  • 102,279
  • 44
  • 260
  • 354
0

Please check this :

if let data = dict["data"].dictionary {
    let user = LFUser(dict: data)
    print(user.user_email)
    finished("Success", user)
}


class LFUser: NSObject {

    var user_id: Int?
    var user_email: String?
    var user_username: String?

    init(dict: [String : SwiftyJSON.JSON]){
        super.init()
        user_id = dict["user_id"]?.intValue
        user_email = dict["user_email"]?.stringValue
        user_username = dict["user_username"]?.stringValue
    }
}
Vini App
  • 7,339
  • 2
  • 26
  • 43