[英]Making an api request using URLSession.shared.dataTask
I'm making an api request:我正在发出 api 请求:
var urlRaw = bookSummaryReadsDomainUrl + apiKey;
let url = URL(string: urlRaw.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)
let task = URLSession.shared.dataTask(with: url!, completionHandler: { (data, response, error) in
if let error = error {
print("Error with fetching book summary reads: \(error)")
return
}
guard let httpResponse = response as? HTTPURLResponse,
(200...299).contains(httpResponse.statusCode) else {
print("Error with the response, unexpected status code: \(response)")
return
}
if let data = data,
let flurryItems = try? JSONDecoder().decode(FlurrySummary.self, from: data) {
completionHandler(flurryItems.rows ?? [])
}
})
task.resume()
to an endpoint that returns the following data到返回以下数据的端点
{
"rows": [
{
"dateTime": "2020-07-04 00:00:00.000-07:00",
"event|name": "BookSummaryRead",
"paramName|name": "bookId",
"paramValue|name": "elon-musk",
"count": 12
},
... ] ... ]
import Foundation
struct FlurrySummary: Codable {
var rows: [FlurryItem]?
enum CodingKeys: String, CodingKey {
case rows = "rows"
}
}
struct FlurryItem: Codable {
var name: String?
var event: String?
var value: String?
var count: String?
var date: String?
enum CodingKeys: String, CodingKey {
case name = "paramName|name"
case event = "event|name"
case value = "paramValue|name"
case count = "count"
case date = "dateTime"
}
}
For some reason the JSONDecoder.decode part is not working.由于某种原因 JSONDecoder.decode 部分不起作用。 It's not filling up the flurryItems and flurryItems.rows = nil.它没有填满flurryItems 和flurryItems.rows = nil。 What am I doing wrong?我究竟做错了什么?
The property count
in FlurryItem
has to be of type Int
. FlurryItem
中的属性count
必须是Int
类型。
var count: Int?
You have to catch the Error
that are thrown.您必须捕获抛出的Error
。
do {
if let data = data,
let flurryItems = try JSONDecoder().decode(FlurrySummary.self, from: data) {
completionHandler(flurryItems.rows ?? [])
}
} catch { print(error) }
Also, you don't need the CodingKeys
in FlurrySummary
since the property name is the same.此外,您不需要CodingKeys
中的FlurrySummary
,因为属性名称相同。
struct FlurrySummary: Codable {
var rows: [FlurryItem]?
}
Note: Also, avoid using optional
declaration if the property never becomes null
.注意:此外,如果属性永远不会变为null
,请避免使用optional
声明。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.