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. You perform most of your configuration on the URL request object itself.NSURLRequest objects represent a URL load request and URL scheme. NSURLRequest encapsulates two basic data elements of a load request: the URL to load, and the policy to use when consulting the URL content cache made available by the implementation. This class serves only to encapsulate information about a URL request. You must use other classes  NSURLConnection to send these requests to a server.

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

1. didReceiveResponse :
func connection(didReceiveResponse: NSURLConnection!, didReceiveResponse response: NSURLResponse!) {
   // Received a new request, clear out the data object = NSMutableData()
2. didReceiveData :
func connection(connection: NSURLConnection!, didReceiveData data: NSData!) {
   // Append the received chunk of data to our data object
3. connectionDidFinishLoading :
func connectionDidFinishLoading(connection: NSURLConnection!) {
   // Request complete, 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


How to call webservice in swift - NSURLConnection? How to call webservice in swift - NSURLConnection? Reviewed by Kirit Modi on 00:10:00 Rating: 5

No comments:

Powered by Blogger.