简体   繁体   English

使用 Alamofire 5 快速解析

[英]Parsing using in swift using Alamofire 5

I am trying to parse this api response but I am getting this error我正在尝试解析此 api 响应,但出现此错误

"Could not cast value of type '__NSDictionaryI' (0x1e06425d8) to 'NSData' (0x1e06418e0)" “无法将'__NSDictionaryI'(0x1e06425d8)类型的值转换为'NSData'(0x1e06418e0)”

. . Here is my code, api response and model class.这是我的代码、api 响应和模型类。

class func getCityApi(viewController: UIViewController,
                      completion:@escaping (_ result:[CityDetails])->(),
                      errorHandler:@escaping (_ result:Error,_ statusCode:Int?)->()
) {

    AF.request(KCity, method: .get, parameters: nil, headers: nil).responseJSON { response in
        switch response.result{
        case.success(let data):
            do{
                let jsonData = try JSONDecoder().decode(City.self, from: data as! Data)
                print(jsonData)
                completion(jsonData.data)
            }
            catch{

            }

        case .failure(let error):
            print(error.localizedDescription)
        }
    }
}

Api Response structrue Api 响应结构

在此处输入图片说明

Model Class模型类

struct City: Codable {
  var data: [CityDetails]
  var status: Bool
  var message: String
}

struct CityDetails: Codable{
  var id: Int
  var location: String
}

You need a Data response.您需要一个Data响应。 Replace代替

AF.request(KCity, method: .get, parameters: nil, headers: nil).responseJSON { response in

with

AF.request(KCity, method: .get, parameters: nil, headers: nil).responseData { response in

and

let jsonData = try JSONDecoder().decode(City.self, from: data as! Data)

with

let jsonData = try JSONDecoder().decode(City.self, from: data)
let jsonData = try JSONDecoder().decode(City.self, from: data as! Data)

将其更改为

let jsonData = try JSONDecoder().decode(City.self, from: data as! Dictionary<String,Any>)

If you already have a Decodable type, you can just use responseDecodable directly, no need to parse the response yourself:如果你已经有一个Decodable类型,你可以直接使用responseDecodable ,不需要自己解析响应:

AF.request(KCity).responseDecodable(of: City.self) { response in
    // response is DataResponse<City, AFError>
}

You can find out more by reading Alamofire's Usage documentation .您可以通过阅读 Alamofire 的使用文档了解更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM