简体   繁体   English

Api 请求 IOS 使用乱舞 api

[英]Api request IOS using flurry api

I have the following code that makes an API request to a flurry.com API endpoint and decodes the request.我有以下代码向 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 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()

The problem is that I cannot use.decode(FlurryItem.self, because the values I get back from the API endpoint is this:问题是我不能使用.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
}]

notice how the variable name is "paramName|name".注意变量名称是“paramName|name”。 The | | makes it impossible to name a variable for that item.使得无法为该项目命名变量。 What can I do instead?我能做些什么呢?

1- You need to use enum 1-您需要使用枚举

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- You should use [FlurryItem].self 2- 你应该使用[FlurryItem].self

let flurryItems = try? JSONDecoder().decode([FlurryItem].self, from: data)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM