ios、alamofire中的响应处理问题
Posted
技术标签:
【中文标题】ios、alamofire中的响应处理问题【英文标题】:respsonse Handling problem in ios, alamofire 【发布时间】:2020-05-16 17:13:25 【问题描述】:我尝试使用 alamofire 进行 API 调用。当我像这样print(response.value ?? "")
打印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
)
【问题讨论】:
【参考方案1】:如错误消息中所述,将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
【讨论】:
我更改了我的代码,但也收到了错误keyNotFound(CodingKeys(stringValue: "title", intValue: nil), Swift.DecodingError.Context(codingPath: [_JSONKey(stringValue: "Index 0", intValue: 0)], debugDescription: "No value associated with key CodingKeys(stringValue: \"title\", intValue: nil) (\"title\").", underlyingError: nil))
我在我的Order
struct codingKeys 中添加了这样的enum CodingKeys: String, CodingKey ...
@RezoJoglidze 似乎响应有一些空值。尝试将一些 Order
属性更改为可选项。例如:struct Order: Codable let title: String? let details: String? let BookingId: Int? public init(from decoder: Decoder) throws let values = try decoder.container(keyedBy: CodingKeys.self) title = try? values.decodeIfPresent(String.self, forKey: .title) details = try? values.decodeIfPresent(String.self, forKey: .details) BookingId = try? values.decodeIfPresent(Int.self, forKey: .BookingId)
我改变了一切,就像你上一个答案一样。在做,我写了这行print (orders)
.
我这样下单,每个字段都是nil [AppName.Order(title: nil, details: nil,BookingId: nil)]
以上是关于ios、alamofire中的响应处理问题的主要内容,如果未能解决你的问题,请参考以下文章
如何检查网络响应来自 Alamofire 请求中的缓存或服务器?