我试图用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
}
)
正如错误信息上所说的那样,将 response.value
到 Order
不会工作。你应该使用 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
}