2017-03-27 4 views
0

Le code suivant fonctionne parfaitement pour une requête http simple. Cependant, je ne peux pas trouver un moyen d'ajouter une charge utile ou une chaîne de caractères dans Swift 3? et les versions précédentes sont dépréciésURLSession.shared.dataTask avec corps/charge utile

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

} 

Répondre

2

Vous devez utiliser URLRequest pour cela et ensuite faire appel à cette demande.

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