如何使用alamofire在模型中存储服务的响应 [英] how to store the response of a service in a model with alamofire
问题描述
我正在学习快速编程,我之前使用android开发了服务消耗,并借助改造和可序列化将它们存储在模型中。现在,我迅速地使用Alamofire 4.0和SwiftyJson来使用服务,问题是如何将所有响应JSON保存在模型中,然后使用此数据,我已经查看了几个示例,但我仍然不知道如何做。
您能告诉我怎么做或我需要添加什么来完成此操作以获取信息,然后使用它
以便我使用该服务
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)
}
}
}
}
这是我的模型
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
}
这是响应中的json
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": ""
}
我收到此错误
keyNotFound(CodingKeys(stringValue: firstName,intValue:nil ),Swift.DecodingError.Context(codingPath:[CodingKeys(stringValue: user,intValue:nil)]],debugDescription:没有与键CodingKeys相关联的值(stringValue:\ firstName\,intValue:nil)( \ firstName\)。,底层错误:nil))
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))
推荐答案
为什么SwiftyJSON?不用了将JSON解析为模型 Decodable
更容易使用,并且它是内置的(无依赖项)。
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) }
}
}
}
这篇关于如何使用alamofire在模型中存储服务的响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!