iosswiftflurryflurry-analytics

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.

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:

[{
     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". The | makes it impossible to name a variable for that item. What can I do instead?


Solution

  • 1- You need to use 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- You should use [FlurryItem].self

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