English 中文(简体)
Accessing Web Services
  • 时间:2024-09-17

Accessing Web Services


Previous Page Next Page  

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

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 apppcation to communicate to the web service, if the service is not https. We will make these changes in the info.ppst 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 apppcation using URL sessions.

Alamofire

Alamofire is a HTTP networking pbrary written in swift. It can be used to make URL Requests, Post Data, Receive Data, Upload File, Data, Authentication, Vapdation, 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 Handpng

The following command is used for response handpng.

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 seriapzation       
   if let JSON = response.result.value {          
      print("JSON: (JSON)")   
   } 
}  

Response Vapdation

The following command is used for response handpng.

Alamofire.request("https://httpbin.org/get").vapdate().responseJSON {  
   response in      
   switch response.result {      
      case .success:         
      print("Vapdation 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