URLSession.shared.dataTask with body / payload

时间:2017-03-27 12:51:50

标签: swift3 httprequest nsurlsessiondatatask urlsession

以下代码适用于简单的http请求。但是我找不到在Swift 3中添加有效载荷或正文字符串的方法?以前的版本是折旧的

  func jsonParser(urlString: String, completionHandler: @escaping (_ data: NSDictionary) -> Void) -> Void
{
    let urlPath = urlString
    guard let endpoint = URL(string: urlPath) else {
        print("Error creating endpoint")
        return
    }

    URLSession.shared.dataTask(with: endpoint) { (data, response, error) in
        do {
            guard let data = data else {
                throw JSONError.NoData

            }
            guard let json = try JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary else {
                throw JSONError.ConversionFailed
            }
            completionHandler(json)
        } catch let error as JSONError {
            print(error.rawValue)

        } catch let error as NSError {
            print(error.debugDescription)
        }
        }.resume()

}

1 个答案:

答案 0 :(得分:6)

您需要使用URLRequest,然后使用该请求进行调用。

var request = URLRequest(url: endpoint)
request.httpMethod = "POST"
let postString = "postDataKey=value"
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
    do {
        guard let data = data else {
            throw JSONError.NoData

        }
        guard let json = try JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary else {
            throw JSONError.ConversionFailed
        }
        completionHandler(json)
    } catch let error as JSONError {
        print(error.rawValue)

    } catch let error as NSError {
        print(error.debugDescription)
    }
}
task.resume()