简体   繁体   中英

Making an api request using URLSession.shared.dataTask

I'm making an api request:

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. It's not filling up the flurryItems and flurryItems.rows = nil. What am I doing wrong?

The property count in FlurryItem has to be of type Int .

var count: Int?

You have to catch the Error that are thrown.

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.

struct FlurrySummary: Codable {
    var rows: [FlurryItem]?
}

Note: Also, avoid using optional declaration if the property never becomes null .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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