1

以下代码非常适合简单的 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()

}
4

1 回答 1

8

您需要使用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()
于 2017-03-27T13:00:00.257 回答