如何使用 alamofire 将服务的响应存储在模型中
how to store the response of a service in a model with alamofire
我正在 swift 学习编程,我以前用 android 开发服务消费,并借助改造和可序列化将它们存储在模型中。现在在 swift 中,我使用 Alamofire 4.0 和 SwiftyJson 来使用服务,问题是如何将所有响应 JSON 保存在模型中,然后使用这些数据,我已经查看了几个示例,但我仍然不明白该怎么做。
你能告诉我怎么做吗或者我需要添加什么来完成这个动作来获取信息然后使用它
所以我使用服务
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
{
"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: "No value associated with key CodingKeys(stringValue: \"firstName\", intValue: nil) (\"firstName\").", underlyingError: nil))
import SwiftyJSON
在 class 中你写了 loginService API 并且在成功的情况下写:
case .success(let value):
let json = JSON(value)
let loginModel = LoginResponse(json: json)
print("Login Model is: \(loginModel)")
看看它是否有效
为什么选择 SwiftyJSON?你不需要那个。将 JSON 解析为模型 Decodable
更容易使用并且它是 built-in (无依赖性)。
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) }
}
}
}
我正在 swift 学习编程,我以前用 android 开发服务消费,并借助改造和可序列化将它们存储在模型中。现在在 swift 中,我使用 Alamofire 4.0 和 SwiftyJson 来使用服务,问题是如何将所有响应 JSON 保存在模型中,然后使用这些数据,我已经查看了几个示例,但我仍然不明白该怎么做。 你能告诉我怎么做吗或者我需要添加什么来完成这个动作来获取信息然后使用它 所以我使用服务
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 {
"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: "No value associated with key CodingKeys(stringValue: \"firstName\", intValue: nil) (\"firstName\").", underlyingError: nil))
import SwiftyJSON
在 class 中你写了 loginService API 并且在成功的情况下写:
case .success(let value):
let json = JSON(value)
let loginModel = LoginResponse(json: json)
print("Login Model is: \(loginModel)")
看看它是否有效
为什么选择 SwiftyJSON?你不需要那个。将 JSON 解析为模型 Decodable
更容易使用并且它是 built-in (无依赖性)。
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) }
}
}
}