Swift 4 Codable Array's

前端 未结 4 1264
半阙折子戏
半阙折子戏 2021-02-02 14:04

So I have an API route that returns a JSON array of objects. For example:

[
    {\"firstname\": \"Tom\", \"lastname\": \"Smith\", \"age\": 31},
    {\"firstname\         


        
4条回答
  •  不要未来只要你来
    2021-02-02 14:53

    I managed to serialize data response to codable objects.

    As all you may have been familiar with converting json object [String: String] for example. That json object need to be converted to Data by using json.data(using: .utf8)!.

    With Alamofire, it is easy to get that data (or at least this kind of data worked for me, already compatible with .utf8 thing), I can just use this already available function

    func responseData(queue: DispatchQueue?, completionHandler: @escaping (DataResponse) -> Void) -> Self
    

    Then just use that data as input for the Decoder in the completionHandler

    let objek = try JSONDecoder().decode(T.self, from: data)
    

    You can also make this to some generic serialization function, with a little tweak, from the documentation

    Generic Response Object Serialization

    to this modification

    func responseCodable(
        queue: DispatchQueue? = nil,
        completionHandler: @escaping (DataResponse) -> Void)
        -> Self
    {
        let responseSerializer = DataResponseSerializer { request, response, data, error in
            guard error == nil else { return .failure(BackendError.network(error: error!)) }
    
            guard let data = data else {
                return .failure(BackendError.objectSerialization(reason: "data is not valid"))
            }
    
    
            do{
                let objek = try JSONDecoder().decode(T.self, from: data!)
                return .success(objek)
            } catch let e {
                return .failure(BackendError.codableSerialization(error: e))
            }
    
        }
    
        return response(queue: queue, responseSerializer: responseSerializer, completionHandler: completionHandler)
    }
    

    Sample struct

    struct Fids: Codable {
    
       var Status: Status?
       var Airport: Airport?
       var Record: [FidsRecord]
    }
    

    Use the function this way

        Alamofire.request("http://whatever.com/zzz").responseCodable { (response: DataResponse) in
            switch response.result{
            case .success(let value):
                print(value.Airport)
            // MARK: do whatever you want
            case .failure(let error):
                print(error)
                self.showToast(message: error.localizedDescription)
            }
        }
    

提交回复
热议问题