Sunday 5 March 2017

Download and upload data to server

In iOS development if we are working on an app which have a backend for managing it's data on the server , we need a mechanism to retrieve and push our app specific data on the server . To implement this , Apple provides a class NSURLSession. NSURLSession provides all method and properties for uploading and downloading data from the server .

Here I am introducing a brief introduction of how to use NSURLSession class . For more deep details  you can go to documentation of NSURLSession class on apple's site.

NSURLSeesion API can be used in two ways:

1) With system provided delegates
2) With custom delegates

We should use custom delegates if our application does one of the following tasks:
1) App uses background session to download and upload content
2) Perform custom authentication
3) Limits caching programmatically
4) Limits HTTP redirects programmatically
5) Perform custom SSL certificate verification

 The life cycle of system provided delegates :

1) Create a session configuration object. For a background session , this configuration must contain a unique identifier. We must store that identifier to use it to reassociate with the session, if app crashes or is terminated or suspended .
2) Create a URLSession object ,specifying  a configuration object and a nil delegate.
3) Create a task object within a session that each represent a resource request and call resume on task because each task starts out in a suspended state. We must call resume on the task  in order to begin the task.

  Characteristics of a task object:

  • The task object is  a subclass of NSURLSessionTask, NSURLSessionDataTask, NSURLSessionUploadTask,NSURLSessionDownloadTask. 
  • We can add more than one task to a session. 
  • If we are using NSURLSession without  providing a delegate, we must create a task using a call that takes a completionHandler parameter. 
  • For a download task :
    • To pause the download, cancel the task by calling 
      • CancelByProducingResumeData
    • To continue the resumed download, pass the resumed data from above method to one of two methods:
      • downloadTaskWithResumeData:
      • downloadTaskWithResumeData:completionHandler:
    • When a task completes , NSURLSession object calls the task's completion handler.
4) When a session is no longer needed, call
             invalidateAndCancel 
     or
             finishTaskAndInvalidate
according to your requirement.

Note: NSURLSession doesn't report server error through the error parameter . The error parameter only show the client side error. To handle server side errors, we must check status code of the task  in HTTPURLSessionResponse object.

1 comment:

  1. Casinos Near Harrah's Lake Tahoe - MapYRO
    A map 오산 출장안마 showing casinos 군포 출장샵 and other gaming facilities 오산 출장안마 located near Harrah's Lake Tahoe 하남 출장마사지 in Stateline, NV. Harrah's Lake Tahoe · Harrah's Lake 화성 출장마사지 Tahoe.

    ReplyDelete