简体   繁体   English

使用 URLSession.shared.dataTask 发出 api 请求

[英]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.

相关问题 Swift URLSession.shared.dataTask GET Request -1001返回超时 - Swift URLSession.shared.dataTask GET Request -1001 returns timeout 在URLSession.shared.dataTask之后调用performSegue - Call performSegue after URLSession.shared.dataTask URLSession.shared.dataTask 冻结 UI - URLSession.shared.dataTask freezes the UI 在URLSession.shared.dataTask中执行performSegueWithIdentifier(with:url) - performSegueWithIdentifier while in URLSession.shared.dataTask(with: url) 如何获取请求中标头的值(URLSession.shared.dataTask(with:request){(数据,响应,错误) - How get value of headers in request (URLSession.shared.dataTask(with: request) { (data, response, error) 当应用程序处于后台时调用URLSession.shared.dataTask - Invoke URLSession.shared.dataTask when the app is background 在URLSession.shared.dataTask期间从异步关闭存储数据 - Storing data from an asynchronous closure during URLSession.shared.dataTask URLSession.shared.dataTask的完成处理程序内部的闭包 - closure inside completion handler of URLSession.shared.dataTask 使用URLSession.shared.dataTask中的JSON和字典进行Swift 3编译器错误 - Swift 3 Compiler Errors with JSON and Dictionaries within URLSession.shared.dataTask 获取URL响应状态代码URLSession.shared.dataTask - Get http response status code of URLSession.shared.dataTask
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM