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

Posted

技术标签:

【中文标题】如何使用 alamofire 将服务的响应存储在模型中【英文标题】:how to store the response of a service in a model with alamofire 【发布时间】:2019-05-06 16:33:03 【问题描述】:

我正在学习快速编程,我之前使用 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))

【问题讨论】:

【参考方案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) 
            
    

【讨论】:

根据问题中的JSON是这样的。 当然有这个json我只是想知道我做的模型是对的还是有别的方法可以做到 如果您没有收到错误,则模型是正确的。这取决于您收到的真实 JSON。 如果它有效,但现在我只有这个疑问,因为我正在测试它,它给了我以下错误,我已经更新了我的 json,我想根据你的例子知道我的型号应该是。 我更新了答案。要将 snake_cased 键转换为 camelCased 结构成员,您必须将 .convertFromSnakeCase 键解码策略添加到解码器。【参考方案2】:

import SwiftyJSON 在您编写 loginService API 的类中并在成功案例中写入:

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

看看有没有效果

【讨论】:

以上是关于如何使用 alamofire 将服务的响应存储在模型中的主要内容,如果未能解决你的问题,请参考以下文章

我如何使用 fetch API 并在状态下存储响应?

如何将 map() 与来自 axios 响应的数据一起使用?

如何在 MYSQL 数据库中存储 API JSON 响应

如何将来自 dataTaskWithUrl 的响应存储在其他变量中?

如何使用目标 C 将 JSON 响应存储到 NSPredicate 中?

如何将改造 JSON 响应转换为列表?