【问题标题】:URLSession.shared.dataTask with body / payloadURLSession.shared.dataTask 与 body / payload
【发布时间】:2017-08-20 04:43:09
【问题描述】:

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

}

【问题讨论】:

    标签: swift3 httprequest nsurlsessiondatatask urlsession


    【解决方案1】:

    您需要为此使用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()
    

    【讨论】:

    • 你是我的英雄,我搜索了很长时间,但我只找到了如何做 JSON Post 而不是字符串帖子,非常感谢!
    猜你喜欢
    • 2021-12-06
    • 1970-01-01
    • 2019-09-16
    • 2020-01-28
    • 1970-01-01
    • 1970-01-01
    • 2018-11-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多