Call API Using URLSession In Swift
This is Basic way to Call API in swift .
1- Create swift playground file like ApiCall.playground .
ApiCall is name of file and .playground is extension of file.
2- Write the Code into this file ApiCall.playground
import UIKit import PlaygroundSupport PlaygroundPage.current.needsIndefiniteExecution = true //this API Call Function func getAPIDataFromServer(){ let session = URLSession.shared let serviceUrl = URL(string: "https://jsonplaceholder.typicode.com/todos/1") let task = session.dataTask(with:serviceUrl!) { (serviceData, serviceResponse, error) in if error == nil{ let httpResponse = serviceResponse as! HTTPURLResponse if(httpResponse.statusCode == 200){ // data parse let jsonData = try? JSONSerialization.jsonObject(with: serviceData!, options: .mutableContainers) let result = jsonData as! Dictionary<String, Any> print("id = \(result["id"]!)") } } }
task.resume() }
//This function call for use
getAPIDataFromServer()
Comments
Post a Comment