答复处理ios中的问题,alamofire。

问题描述 投票:0回答:1

我试图用alamofire进行API调用,当我打印出 response.value 这样 print(response.value ?? "") 我在Xcode控制台中得到了正确的文本,但我得到了一个错误,这一行 comletionHanlder(response.value as! [Order]).

错误信息是 Could not cast value of type '__NSDictionaryI' (0x7f81db0f3070) to 'AppName.Order' (0x10db3fb80)

static func getOrders( comletionHanlder: @escaping ([Order]) -> Void){
    let headers : HTTPHeaders = ["Authorization" : "Bearer \(User.current!.accessToken)",
                "Lang"          : "KA"]

    let urlStr = Constants.Api.baseUrl + Constants.Api.Routes.api + Constants.Api.Routes.doctorBooking + Constants.Api.Routes.getBookings

    AF.request(urlStr,
               method: .post,
               encoding: JSONEncoding.default,
               headers: headers).responseJSON{ response in

               if response.response?.statusCode == 400 {
                    comletionHanlder([])
                } else {
                if response.response?.statusCode == 200 {
                    print(response.value ?? "")
                    comletionHanlder(response.value as! [Order])
                }
          }
    }

;

struct Order: Codable {
    let title: String
    let details: String
    let BookingId: Int
}

当我打印 response.value我收到了这个消息

(
    {
      title = "title"
      details = "details"
      BookingId = 10002
     },
     {
      title = "title1"
      details = "details1"
      BookingId = 10003
     }
)
ios swift networking alamofire
1个回答
0
投票

正如错误信息上所说的那样,将 response.valueOrder 不会工作。你应该使用 JSONDecodable 类来解码所需订单列表的响应,就像这样。

guard let responseData = response.data else { /* do something */ }    
do {
    let orders = try JSONDecoder().decode([Order].self, from: responseData)
    debugPrint(orders)
} catch {
    // handle the error
}
© www.soinside.com 2019 - 2024. All rights reserved.