I'm trying to use Swift to make a GET call to a REST API, and have tried to follow numerous tutorials, but can't figure it out. Either because I cannot figure out how to translate all the Obj-C to Swift, or because half of the methods n' such are deprecated. Does anyone know how to make the call, and parse returned JSON data?
Step #1 – Enter the URL of the API in the textbox of the tool. Step #2 – Select the HTTP method used for this API (GET, POST, PATCH, etc). Step #3 – Enter any headers if they are required in the Headers textbox. Step #4 – Pass the request body of the API in a key-value pair.
REST APIs are based on the HTTP protocol, which is the communication protocol used by the world wide web. Understanding HTTP means knowing how URLs are structured, what actions you can express using HTTP methods, how you can express parameters in a request, and how to send or receive data.
Before we start, we need to define the URL of the remote image. import UIKit let url = URL(string: "https://bit.ly/2LMtByx")! The next step is creating a data task, an instance of the URLSessionDataTask class. A task is always tied to a URLSession instance.
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.shared let 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 ofNSDictionary
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With