Make REST API call in Swift Make REST API call in Swift ios ios

Make REST API call in Swift


Swift 5 & 4

let params = ["username":"john", "password":"123456"] as Dictionary<String, String>var request = URLRequest(url: URL(string: "http://localhost:8080/api/1/login")!)request.httpMethod = "POST"request.httpBody = try? JSONSerialization.data(withJSONObject: params, options: [])request.addValue("application/json", forHTTPHeaderField: "Content-Type")let session = URLSession.sharedlet task = session.dataTask(with: request, completionHandler: { data, response, error -> Void in    print(response!)    do {        let json = try JSONSerialization.jsonObject(with: data!) as! Dictionary<String, AnyObject>        print(json)    } catch {        print("error")    }})task.resume()


You can do like this :

var url : String = "http://google.com?test=toto&test2=titi"var request : NSMutableURLRequest = NSMutableURLRequest()request.URL = NSURL(string: url)request.HTTPMethod = "GET"NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue(), completionHandler:{ (response:NSURLResponse!, data: NSData!, error: NSError!) -> Void in    var error: AutoreleasingUnsafeMutablePointer<NSError?> = nil    let jsonResult: NSDictionary! = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers, error: error) as? NSDictionary    if (jsonResult != nil) {        // process jsonResult    } else {       // couldn't load JSON, look at error    }})

EDIT : For people have problem with this maybe your JSON stream is an array [] and not an object {} so you have to change jsonResult to NSArray instead of NSDictionary


I think the NSURLSession api fits better in this situation. Because if you write swift code your project target is at least iOS 7 and iOS 7 supports NSURLSession api. Anyway here is the code

let url = "YOUR_URL"NSURLSession.sharedSession().dataTaskWithURL(NSURL(string: url)) { data, response, error in    // Handle result}.resume()