how to store the response of a service in a model with alamofire

主宰稳场 提交于 2019-12-13 03:04:28

问题


I am learning to programme in swift, I developed with android previously the consumption of services and stored them in a model with the help of retrofit and serializable. Now in swift, I use the Alamofire 4.0 and SwiftyJson to consume a service and the problem is how to save all the response JSON in a model and then use this data, I have reviewed several examples but I still do not understand how to do it. Could you tell me how to do it or what I need to add to complete this action to get the information and then use it so I consume the service

static func loginService(email : String, password : String, completionHandler : @escaping (LoginResponse) -> Void){
        let parameters : Parameters  = ["email": email, "password": password]
        Alamofire.request(AlamofireConstants.LOGIN, method: .post, parameters: parameters, encoding: URLEncoding.default).validate(statusCode: 200..<300).responseData { response in
            switch response.result {
            case .failure(let error):
                print("error ==> \(error)")
            case .success(let data):
                do{
                    let result = try JSONDecoder().decode(LoginResponse.self, from: data)
                    print(result)
                } catch {
                    print(error)
                }
            }
        }
    }

this is my model

    struct LoginResponse : Decodable {
    let user : User?
    let status: Int
    let success: Bool
    let message: String
}

struct User : Decodable {
    let id: Int
    let firstName, lastName, surName, email: String
    let emailToken: String?
    let validate: String
    let token, nationality, documentType, documentNumber: String?
    let legalName, legalNumber, birthdate: String?
    let gender: String
    let phoneMovil, phoneFix, icon: String?
    let wishOffers, acceptTerms, isCustomer: Int
    let active: Bool
    let createdAt, updatedAt: String
}

and this is the json from response

  {
"user": {
    "id": 183,
    "first_name": "teste",
    "last_name": "testet",
    "sur_name": "este",
    "email": "adeveloper964@gmail.com",
    "email_token": null,
    "validate": "S",
    "token": null,
    "nationality": null,
    "document_type": null,
    "document_number": null,
    "legal_name": null,
    "legal_number": null,
    "birthdate": null,
    "gender": "O",
    "phone_movil": null,
    "phone_fix": null,
    "icon": null,
    "wish_offers": 0,
    "accept_terms": 1,
    "is_customer": 0,
    "active": true,
    "created_at": "2019-05-13 17:04:50",
    "updated_at": "2019-05-14 10:19:31"
},
"status": 0,
"success": true,
"message": ""

}

I get this error

keyNotFound(CodingKeys(stringValue: "firstName", intValue: nil), Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "user", intValue: nil)], debugDescription: "No value associated with key CodingKeys(stringValue: \"firstName\", intValue: nil) (\"firstName\").", underlyingError: nil))


回答1:


Why SwiftyJSON? You don't need that. To parse JSON into a model Decodable is much easier to use and it's built-in (no dependencies).

struct LoginResponse : Decodable {

    let user: User
    let status: Int
    let success : Bool
    let message : String
}

struct User : Decodable {
    let id : Int
    let firstName, lastName, surName, email : String
}


static func loginService(user : String, password : String){
    Alamofire.request(AlamofireConstants.BASE_URL_TEST + "/api/loginuser", method: .post, parameters: ["email":user,"password":password], encoding: URLEncoding.default)
        .validate(statusCode: 200..<300)
        .responseData { response in // note the change to responseData
            switch response.result {
            case .failure(let error):
                print(error)
            case .success(let data):
                do {
                    let decoder = JSONDecoder()
                    decoder.keyDecodingStrategy = .convertFromSnakeCase
                    let result = try decoder.decode(LoginResponse.self, from: data)
                    print(result)
                } catch { print(error) }
            }
    }
}



回答2:


import SwiftyJSON in the class where you wrote loginService API and under success case write:

case .success(let value):
  let json = JSON(value)
  let loginModel = LoginResponse(json: json)
  print("Login Model is: \(loginModel)")

and see if it works



来源:https://stackoverflow.com/questions/56009160/how-to-store-the-response-of-a-service-in-a-model-with-alamofire

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!