Tuesday, 25 April 2017

Webservice integration in swift

Introduction


Service integration in application is a trivial task for every programer, apple provides the API to get that task done.  NSURLSession is the key object responsible for sending and receiving HTTP requests.

from apple
"The NSURLSession class and related classes provide an API for downloading content. This API provides a rich set of delegate methods for supporting authentication and gives your app the ability to perform background downloads when your app is not running or, in iOS, while your app is suspended"

URL Session Class Hierarchy

The NSURLSession API consists of the following classes (nested to show subclass relationships):

URLSessionConfiguration

— A configuration object used when initializing the session.
"An NSURLSessionConfiguration object defines the behavior and policies to use when uploading and downloading data using an NSURLSession object. When uploading or downloading data, creating a configuration object is always the first step you must take. You use this object to configure the timeout values, caching policies, connection requirements, and other types of information that you intend to use with your NSURLSessionobject."

which comes in three flavors
  1. defaultSessionConfiguration: Creates a default configuration object that uses the disk-persisted global cache, credential and cookie storage objects.
  2. ephemeralSessionConfiguration: Similar to the default configuration, except that all session-related data is stored in memory. Think of this as a “private” session.
  3. backgroundSessionConfiguration: Lets the session perform upload or download tasks in the background. Transfers continue even when the app itself is suspended or terminated.


URLSessionTask


  • is an abstract class that denotes a task object. A session creates a task, which does the actual work of fetching data and downloading or uploading files.
There are three types of concrete session tasks in this context:

  • NSURLSessionDataTask: Use this task for HTTP GET requests to retrieve data from servers to memory.
  • NSURLSessionUploadTask: Use this task to upload a file from disk to a web service, typically via a HTTP POST or PUT method.
  • NSURLSessionDownloadTask: Use this task to download a file from a remote service to a temporary file location.
NSURLSession Tutorial
You can also suspend, resume and cancel tasks. NSURLSessionDownloadTask has the additional ability to pause for future resumption.

In addition, the NSURLSession API provides four protocols that define delegate methods your app can implement to provide more fine-grained control over session and task behavior.
Finally, the NSURLSession API uses a number of classes that are also commonly used with other APIs such as NSURLConnection and NSURLDownload. Some of these shared classes include:
  • NSURL—An object that contains a URL.
  • NSURLRequest—Encapsulates metadata related to a URL request, including the URL, request method, and so on.
  • URLResponse—Encapsulates metadata related to a server’s response to a request, such as the content MIME type and length.
    • HTTPURLResponse—Adds additional metadata specific to HTTP requests, such as response headers.
  • CachedURLResponse—Encapsulates an URLResponse object, along with the actual body data of the server’s response, for caching purposes.




Example
// Set up the URL request
let todoEndpoint: String = "https://jsonplaceholder.typicode.com/todos/1"
guard let url = URL(string: todoEndpoint) else {
 print("Error: cannot create URL")
 return
}
let urlRequest = URLRequest(url: url)

// set up the session
let config = URLSessionConfiguration.default
// let session = URLSession.shared

let session = URLSession(configuration: config)
// make the request
let task = session.dataTaskWithRequest(urlRequest) {
 (data, response, error) in
 // check for any errors
 guard error == nil else {
   print("error calling GET on /todos/1")
   print(error)
   return
 }
 // make sure we got data
 guard let responseData = data else {
   print("Error: did not receive data")
   return
 }
 // parse the result as JSON, since that's what the API provides
 do {
   guard let todo = try JSONSerialization.jsonObject(with: responseData, options: []) as? [String: AnyObject] else {
  print("error trying to convert data to JSON")
   return
 }
}
   // now we have the todo, let's just print it to prove we can access it
   print("The todo is: " + todo.description
   // the todo object is a dictionary
   // so we just access the title using the "title" key
   // so check for a title and print it if we have one
   guard let todoTitle = todo["title"] as? String else {
     print("Could not get todo title from JSON")
     return
   }
   print("The title is: " + todoTitle)
 } catch  {
   print("error trying to convert data to JSON")
   return
 }
}
task.resume()

Follow this tutorial for more concept oriented use cases








No comments:

Post a Comment