如何使用alamofire在模型中存储服务的响应

时间:2019-05-06 16:33:04

标签: swift xcode alamofire swifty-json

我正在学习快速编程,我之前使用android开发了服务消耗,并借助改造和可序列化将它们存储在模型中。现在,我迅速地使用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:“与键CodingKeys无关的值(stringValue:\“ firstName \”,intValue:无)(\“ firstName \”)。“,底层错误:nil))

2 个答案:

答案 0 :(得分:1)

为什么使用SwiftyJSON?不用了将JSON解析为模型Decodable更加容易使用,并且它是内置的(无依赖项)。

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) }
            }
    }
}

答案 1 :(得分:0)

return this.http .get(`${this.BASE_URL}${tableName}?${queryString}`) .pipe( map((response: Response) => (<GridDataResult>{ data: response.data, total: response.count// parseInt(response.length, 10) })), tap(() => this.loading = false) ); 在您编写了loginService API的类中,并在成功的情况下编写:

import SwiftyJSON

看看是否可行