Accessing Web Services

In our application, we might need to connect to API and retrieve data from that API and use in our application.

Firstly, we need the URL, which will provide us the data.

After that, we need to add transport layer security exception to allow our application to communicate to the web service, if the service is not https. We will make these changes in the info.plist file.

Finally, we will create an URLSession to create a network request.

let urlString = URL(string: "your URL")  // Making the URL  
if let url = urlString {   
   let task = URLSession.shared.dataTask(with: url) { 
      (data, response, error) in // Creating the URL Session. 
      if error != nil {  
         // Checking if error exist. 
      } else { 
         if let usableData = data { 
            // Checking if data exist. 
            // printing Data. 

This is how you can Use Web services in your application using URL sessions.


Alamofire is a HTTP networking library written in swift. It can be used to make URL Requests, Post Data, Receive Data, Upload File, Data, Authentication, Validation, etc.

To install Aalmofire, you can go to Alamofire officially on GitHub, and read their installation guide

Making a Request in Alamofire

For making a request in Alamofire, we should use the following command.

Import Alamofire 

Response Handling

The following command is used for response handling.

Alamofire.request("url").responseJSON {  
   response in      
   // original URL request     
   // HTTP URL response      
   // server data      
   // result of response serialization       
   if let JSON = response.result.value {          
      print("JSON: \(JSON)")   

Response Validation

The following command is used for response handling.

Alamofire.request("").validate().responseJSON {  
   response in      
   switch response.result {      
      case .success:         
      print("Validation Successful")      
      case .failure(let error):      

These are the basics of making URL request, using URL Sessions and Alamofire. For more advanced Alamofire, please visit Alamofire Documentation, and you can read about it in detail.

Kickstart Your Career

Get certified by completing the course

Get Started