2017-03-27 67 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() 
相關問題