W3Schools Learner's Blog

W3Schools Programming knowledge summary website



How To Call Webservice in Swift - NSURLConnection?

 An NSURLConnection object lets you load the contents of a URL by providing a URL request object. The interface for NSURLConnection is sparse, providing only the controls to start and cancel asynchronous loads of a URL request. 

Declare array as below :
1var data: NSMutableData = NSMutableData()
Making the API Request :
12var request: NSURLRequest = NSURLRequest(URL: url)
var connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: false)
Receiving response to Calling Delegate :

1. didReceiveResponse :
1234func connection(didReceiveResponse: NSURLConnection!, didReceiveResponse response: NSURLResponse!) {
   // Received a new request, clear out the data object
   self.data = NSMutableData()
2. didReceiveData :
1234func connection(connection: NSURLConnection!, didReceiveData data: NSData!) {
   // Append the received chunk of data to our data object
3. connectionDidFinishLoading :
12345678910111213func connectionDidFinishLoading(connection: NSURLConnection!) {
   // Request complete, self.data should now hold the resulting info
   // Convert the retrieved data in to an object through JSON deserialization
   var err: NSError
   var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary

   if jsonResult.count>0 && jsonResult["results"].count>0 {
      var results: NSArray = jsonResult["results"] as NSArray
      self.tableData = results


Demo project : NSURLRequest-Swift-Demo


No comments:

Post a Comment

Note: only a member of this blog may post a comment.