Accessing Web Services


Advertisements

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.

api.openweathermap.org/data/2.5/forecast?id=524901&APPID=1111111111

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. 
         print(error) 
      } else { 
         if let usableData = data { 
            // Checking if data exist. 
            print(usableData)   
            // printing Data. 
         } 
      } 
   }
}	
task.resume() 

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

Alamofire

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 
Alamofire.request("url");

Response Handling

The following command is used for response handling.

Alamofire.request("url").responseJSON {  
   response in      
   print(response.request)   
   // original URL request     
   print(response.response)  
   // HTTP URL response      
   print(response.data)      
   // server data      
   print(response.result)    
   // 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("https://httpbin.org/get").validate().responseJSON {  
   response in      
   switch response.result {      
      case .success:         
      print("Validation Successful")      
      case .failure(let error):      
      print(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.

Advertisements