Advertisement
neatekFb

JSON Get data from API - POST Request - Swift 3

Nov 2nd, 2016
548
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 1.27 KB | None | 0 0
  1. // Vladimir Zhelnov - neatek.pw - Web/iOS dev
  2. class Class_JSONRequest {    
  3.     func get_url_post(get_url: String, params: String, completion: @escaping (_ result: NSDictionary) -> Void) {
  4.         let myUrl = URL(string: get_url);
  5.         var request = URLRequest(url:myUrl!)
  6.         request.httpMethod = "POST"
  7.         let postString = params;
  8.         request.httpBody = postString.data(using: String.Encoding.utf8);
  9.         let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
  10.             if error != nil
  11.             {
  12.                 print("error=\(error)")
  13.                 return
  14.             }
  15.             do {
  16.                 if(data != nil) {
  17.                     let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
  18.                     if let parseJSON = json {
  19.                         //print(parseJSON)
  20.                         completion(parseJSON)
  21.                     }
  22.                 }
  23.             } catch {
  24.                 print(error)
  25.             }
  26.         }
  27.         task.resume()
  28.     }
  29. }
  30. /* usage:
  31. let post_params = "some=post&params=1";
  32. JSON.get_url_post(get_url: "http://..api", params: post_params , completion: { answer in
  33.     ... something
  34. });
  35. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement