How to call webservice using NSURLSession?

NSURLSessionTask is an abstract subclass, with three concrete subclasses that are used directly: NSURLSessionDataTask, NSURLSessionUploadTask, 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 :

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

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

                        print(jsonResult)
                    }
                }
               catch{

                    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"
    task.resume()

Thanks :

How to call webservice using NSURLSession? How to call webservice using NSURLSession? Reviewed by KIRIT MODI on 22:19:00 Rating: 5

No comments:

Powered by Blogger.