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 :
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
self.data = NSMutableData()
}
2. didReceiveData :
func connection(connection: NSURLConnection!, didReceiveData data: NSData!) {
// Append the received chunk of data to our data object
self.data.appendData(data)
}
3. connectionDidFinishLoading :
func 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
self.appsTableView.reloadData()
}
}
Demo project : NSURLRequest-Swift-Demo
Thanks
How To Call Webservice in Swift - NSURLConnection?
Reviewed by KIRIT MODI
on
00:10:00
Rating:
No comments: