使用flurry Api的Api请求IOS
我有以下代码向flurry.com API端点发出API请求并解码该请求使用flurry Api的Api请求IOS,ios,swift,flurry,flurry-analytics,Ios,Swift,Flurry,Flurry Analytics,我有以下代码向flurry.com API端点发出API请求并解码该请求 let url = URL(string: bookStarRateDomainUrl)! let task = URLSession.shared.dataTask(with: url, completionHandler: { (data, response, error) in if let error = error { print("Error with fetching book sta
let url = URL(string: bookStarRateDomainUrl)!
let task = URLSession.shared.dataTask(with: url, completionHandler: { (data, response, error) in
if let error = error {
print("Error with fetching book star rates: \(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(FlurryItem.self, from: data) {
completionHandler(flurryItems.results ?? [])
}
})
task.resume()
问题是我无法使用.decode(FlurryItem.self),因为我从API端点返回的值如下:
[{
dateTime:2020-06-05 00:00:00.000-07:00
event|name:BookStarRate
paramName|name:bookId
paramValue|name:why-buddism-is-true
count:3
}]
请注意变量名是如何“paramName | name”的。|使得无法为该项命名变量。我可以做些什么呢?1-您需要使用enum
struct Root: Codable {
var date: String
var name: String
var id: Int
var value: String
var count: Int
enum CodingKeys: String, CodingKey {
case date = "dateTime"
case name = "event|name"
case id = "paramName|name"
case value = "paramValue|name"
case count
}
}
2-您应该使用[FlurryItem].self
let flurryItems = try? JSONDecoder().decode([FlurryItem].self, from: data)
这根本不是我要说的。解码行工作得非常好。问题是键名中有一个指向点1的|,而你的解码将不能作为
[{}]
是一个数组json,当您解码字典时FlurryItem对象类是什么样子的?您能给我举个例子吗?避免使用try吗?
因为try-catch
块将帮助调试错误