Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make REST API call in Swift

Tags:

rest

http

ios

swift

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?

like image 560
cclloyd Avatar asked Jun 20 '14 06:06

cclloyd


People also ask

How do I create a REST API call?

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.

What is restful API in Swift?

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.

How do you make HTTP requests with URLSession in Swift?

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.


2 Answers

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() 
like image 186
Haroldo Gondim Avatar answered Sep 29 '22 17:09

Haroldo Gondim


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

like image 41
jaumard Avatar answered Sep 29 '22 18:09

jaumard