2017-03-27 60 views
0

以下代码对于简单的http请求来说是完美的。然而,我无法找到一种在Swift 3中添加有效载荷或主体字符串的方法?并且以前的版本是贬值的URLSession.shared.dataTask with body/payload

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() 

} 

回答

2

您需要使用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() 
相关问题