将ecobee Alamofire请求转换为使用URLSession

时间:2019-05-02 16:05:08

标签: swift alamofire urlsession ecobee-api

作为我最后一个问题(Alamofire syntax for ecobee request)的后续,我宁愿只对请求使用URLSession。

现在,我使用以下代码返回状态为408的请求:

guard let url = URL(string: "https://api.ecobee.com/1/thermostat") else { return }

let jsonParameters = [ "selection": [ "selectionType": "registered", "selectionMatch": "" ] ]
let jsonData = try! JSONEncoder().encode(jsonParameters)
let jsonString = String(decoding: jsonData, as: UTF8.self)

let queryParameters = ["format": "json", "body": jsonString]
let headers: HTTPHeaders = [.authorization(bearerToken: AUTH_TOKEN), .contentType("text/json")]

var request = try! URLRequest(url: url, method: .get, headers: headers)
request.httpBody = try! JSONEncoder().encode(queryParameters)

URLSession.shared.dataTask(with: request) { (data, resp, err) in
    debugPrint(String(data: data!, encoding: .utf8)!)
}.resume()

我怀疑我没有正确添加查询参数。

1 个答案:

答案 0 :(得分:0)

我使用UrlComponents找到了自己的解决方案

func testRequest() {
    guard var url = URLComponents(string: "https://api.ecobee.com/1/thermostat") else { return }

    let jsonParameters = [ "selection": [ "selectionType": "registered", "selectionMatch": "" ] ]
    let jsonData = try! JSONEncoder().encode(jsonParameters)
    let jsonString = String(decoding: jsonData, as: UTF8.self)

    let queryParameters = ["format": "json", "body": jsonString]
    url.queryItems = queryParameters.map { URLQueryItem(name: $0.key, value: $0.value) }

    let headers = [
        "Authorization": "Bearer \(core.accessToken)",
        "Content-Type": "application/x-www-form-urlencoded; charset=utf-8"
    ]

    var request = URLRequest(url: url.url!)
    request.httpMethod = "GET"
    request.allHTTPHeaderFields = headers

    URLSession.shared.dataTask(with: request) { (data, resp, err) in
        debugPrint(String(data: data!, encoding: .utf8)!)
    }.resume()
}