ITP 342 Mobile App Dev
REST Philosophy The 3 most important features of a RESTful server are its statelessness, uniform resource identification, and cacheability. Statelessness Every API is treated as a new request, and no client context is remembered on the server. Resource identification Done through URLs Cacheability Allows clients to cache responses based on the URL 2
REST Philosophy Response from a RESTful server is usually sent in a uniform, agreed-upon format, usually to decouple the client/server interface. The client ios app communicates with a RESTful server through this agreed-upon data exchange format. The most commonly used formats are XML and JSON. 3
XML XML stands for extensible Markup Language Designed to transport and store data Uses tags Has a root node http://www.w3schools.com/xml/default.asp <?xml version="1.0" encoding="utf-8"?>! <note>! <to>jason</to>! <from>trina</from>! <heading>reminder</heading>! <body>bring home some milk!</body>! </note>! 4
JSON JSON stands for JavaScript Object Notation Is a lightweight text-data interchange format Is "self-describing" and easy to understand http://www.w3schools.com/json/ {! }! "employees": [! { "firstname":"trina", "lastname":"gregory" },! { "firstname":"chitvan", "lastname":"gupta" },! { "firstname":"poojan", "lastname":"jhaveri" }! ]! 5
Parsing XML on ios You can do XML parsing using 2 kinds of parsers: A DOM (Document Object Model) parser http://www.w3schools.com/dom/dom_parser.asp A SAX (Simple API for XML) parser XML Parser for ios http://www.raywenderlich.com/553/xml-tutorialfor-ios-how-to-choose-the-best-xml-parser-foryour-iphone-project 6
SAX Parser Most SAX parsers work by taking in a URL as a parameter and giving you data as it becomes available. The NSXMLParser foundation class has a method called initwithcontentsofurl:! You essentially initialize a parser object with the URL, and the NSXMLParser does the rest. Parsed data becomes available through callback via delegate methods defined in NSXMLParserDelgate. 7
NSXMLParser Conform to the NSXMLParserDelegate. The most commonly handled methods are: parserdidstartdocument:! parserdidenddocument:! parser: didstartelement: namespaceuir: qualifiedname: attributes:! parser: didendelement: namespaceuri: qualifiedname:! parser: foundcharacters:! 8
DOM Parser A DOM parser loads the complete XML before it starts parsing. The advantage of using a DOM parser is its capability to access data at random using XPath queries, and there's no delegation as in the SAX model. ios does not have an Objective-C-based DOM parser built in. You can use libxml2 or third-party wrappers such as KissXML, TouchXML, or GDataXML. 9
Parsing JSON on ios JSON is much more commonly used than XML. With ios 5, Apple introduced NSJSONSerialization, which is Apple's JSON parsing and serializing framework. You also can choose from plenty of thirdparty JSON processing frameworks. The most commonly used are SBJson, TouchJSON, YAJL, and JSONKit. 10
Important Reminders Never make a synchronous network call. Even if they're on a background thread, synchronous calls don't report progress. Another reason is that to cancel a synchronous request running on a background thread, you have to kill the thread. Avoid using NSThread or GCD-based threading directly for network operations (unless your project is small and has just a couple of API calls). Use NSOperationQueue-based threading instead. NSOperationQueue helps with controlling the queue length and the number of concurrent network operations. 11
NSURLConnection Apple provides classes in CFNetwork.framework and provides a Foundation-based NSURLConnection for making asynchronous requests. MKNetworkKit is a block-based wrapper around NSURLConnect that doesn't bloat your code base while providing powerful features, most importantly, caching. 12
Resources ios 7 Programming: Pushing the Limits by Rob Napier and Mugunth Kumar Chapter 12: REST for the Weary ios 7 Programming: Pushing the Limits by Rob Napier and Mugunth Kumar Chapter 11: Behind the Scenes: Background Processing 13
Network Access Common background task is making a network request We want to ensure that user data is saved to a server even if the user leaves the app in the middle of your save action In ios 6, we would wrap the network request with beginbackgroundtaskwithexpiration Handler:! Works for small requests 14
New Solution In ios 7, the preferred way is NSURLSession There is no simple, universal way to implement background transfers with NSURLSession Need to adapt it heavily to your specific situation NSURLSession is a replacement for NSURLConnection 15
NSURLSession Previously [NSURLConnection sendasynchronousrequest: queue:! completionhandler: ]! Use [NSURLSession datataskwithurl: completionhandler: ]! 16
NSURLSession Previously [NSURLConnection sendasynchronousrequest: request! queue: [NSOperationQueue mainqueue]! completionhandler: handler];! Use NSURLSessionTask *task = [[NSURLSession sharedsession]! datataskwithrequest: request:! completionhandler: handler];! [task resume];! 17
Session Configuration After this, you can get a few features Query the task for info such as its originalrequest and its countofbytesexpectedtorecieve You can start configuring the session You can configure a session that doesn't use cellular data NSURLSessionConfiguration *configuration =! [NSURLSessionConfiguration defaultsessionconfiguration];! [configuration setallowscellularaccess: NO];! NSURLSession *session = [NSURLSession! sessionwithconfiguration: configuration];! 18
Session Configuration NSURLSession has 3 build-in configurations: defaultsessionconfiguration! Matches the behavior of NSURLConnection Uses the shared cache, cookie storage, etc. ephemeralsessionconfiguration! Uses only in-memory storage Nothing is written to disk backgroundsessionconfiguration:! Takes an identifier and is configured to perform network transfers while your app is in the background, or even when it is terminated 19
Tutorials AppCoda Fetch and Parse JSON http://www.appcoda.com/fetch-parse-json-iosprogramming-tutorial/ AppCoda XML and JSON Parsing http://www.appcoda.com/parse-xml-and-json-webservice/ Ray Wenderlich JSON http://www.raywenderlich.com/5492/working-withjson-in-ios-5 Touch Code Fetch and Parse JSON http://www.touch-code-magazine.com/how-to-fetchand-parse-json-by-using-data-models/ 20
Frameworks AFNetworking networking framework http://afnetworking.com RestKit RESTful framework http://restkit.org http://www.raywenderlich.com/58682/ introduction-restkit-tutorial 21