W3Schools Learner's Blog

W3Schools Programming knowledge summary website



How to call webservice using NSURLSession?

 NSURLSessionTask is an abstract subclass, with three concrete subclasses that are used directly: NSURLSessionDataTaskNSURLSessionUploadTask, and NSURLSessionDownloadTask. These three classes encapsulate the three essential networking tasks of modern applications: fetching data, such as JSON or XML, and uploading and downloading file.When an NSURLSessionDataTask finishes, it has associated data, whereas an NSURLSessionDownloadTask finishes with a temporary file path for the downloaded file. 

NSURLSessionUploadTask inherits from NSURLSessionDataTask, since the server response of an upload often has associated data.  All tasks are cancelable, and can be paused and resumed. When a download task is canceled, it has the option to create resume data, which can then be passed when creating a new download task to pick up where it left off.

Code :

1234567891011121314151617181920  let urlPath = "YourURL"
  let url = NSURL(string: urlPath)
  let session = NSURLSession.sharedSession()
  let task = session.dataTaskWithURL(url!, completionHandler: {data, response, error -> Void in

               if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary {


                    print("Somthing wrong")

    // The task is just an object with all these properties set
    // In order to actually make the web request, we need to "resume"

Thanks :

No comments:

Post a Comment

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