AGENDA NSURLSession Handling JSON Third party networking libraries
NSURLSESSION
NSURLSESSION
Class provided by Foundation library that allows issuing HTTP requests
CANONICAL EXAMPLE let imageView = UIImageView() let url = NSURL(string: "http://www.sbs.com.au/news/sites/sbs.com.au.news/files/styles/ full/public/g1369638954952825892.jpg.png?itok=eI4dUGhC&mtime=1429064409")! let urlRequest = NSURLRequest(URL: url) let session = NSURLSession.sharedSession() let task = session.dataTaskWithRequest(urlRequest) { data, response, error in if let data = data { let image = UIImage(data: data) dispatch_async(dispatch_get_main_queue()) { imageView.image = image } } } task.resume()
CANONICAL EXAMPLE 1. Retrieve a session from NSURLSession 2. Create a task using that session 3. Provide a delegate or callback to deal with the response
NSURLSESSION - TASK TYPES NSURLSessionDataTask: A task for retrieving the contents Not background compatible! of a URL as an NSData object NSURLSessionUploadTask: A task for uploading a file, then retrieving the contents of a URL as an NSData object NSURLSessionDownloadTask: A task for retrieving the contents of a URL as a temporary file on disk Source: NSURLSession reference
Background compatible
POST EXAMPLE let content = ["post": "test content"] let jsonData = try! NSJSONSerialization.dataWithJSONObject(content, options: NSJSONWritingOptions(rawValue: 0)) let urlPost = NSURL(string: "http://jsonplaceholder.typicode.com/posts")! let urlRequestPost = NSMutableURLRequest(URL: urlPost) urlRequestPost.HTTPMethod = "POST" urlRequestPost.HTTPBody = jsonData let postTask = session.dataTaskWithRequest(urlRequestPost) { data, response, error in if let data = data { print(response) } } postTask.resume()
HANDLING JSON
HANDLING JSON
Foundation framework provides NSJSONSerialization Class is poorly suited for Swift π’
HANDLING JSON let jsonOptional: AnyObject! = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(0), error: &jsonErrorOptional) if let json = jsonOptional as? Dictionary<String, AnyObject> { if let id = json["id"] as? Int { if let name = json["name"] as AnyObject? as? String { if let email = json["email"] as AnyObject? as? String { let user = User(id: id, name: name, email: email) callback(user) } } } }
π’π’π’π’π’π’π’π’π’π’π’π’π’ Source: Eο¬cient JSON in Swift with Functional Concepts and Generics
HANDLING JSON For sane JSON parsing code we need to use third party libraries that implement type checking for us There are many libraries available: SwiftyJSON, Argo, Gloss, etc.
HANDLING JSON WITH GLOSSY - 1 struct Post: Glossy { var title: String? var content: String? init?(json: JSON) { self.title = "title" self.title, "content" ~~> self.content ]) } }
HANDLING JSON WITH GLOSSY - 2 let jsonPost = Post(title: "Test", content: "Test Content").toJSON()! let jsonData = try! NSJSONSerialization.dataWithJSONObject(jsonPost, options: NSJSONWritingOptions(rawValue: 0)) let urlPost = NSURL(string: "http://jsonplaceholder.typicode.com/posts")! let urlRequestPost = NSMutableURLRequest(URL: urlPost) urlRequestPost.HTTPMethod = "POST" urlRequestPost.HTTPBody = jsonData urlRequestPost.setValue("application/json", forHTTPHeaderField: "content-type") let postTask = session.dataTaskWithRequest(urlRequestPost) { data, response, error in if let data = data { let json = try! NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(rawValue: 0)) let post = Post(json: json as! JSON) print(post) } } postTask.resume()
THIRD PARTY NETWORKING LIBRARIES
THIRD PARTY NETWORKING Networking code encounters issues that are similar for all diο¬erent kinds of apps Third party libraries help in solving these common problems (e.g. parsing responses from as server)
THIRD PARTY NETWORKING Alamofire: an abstraction on top of NSURLSession with a simplified API Moya: built on top of Alamofire, improves modeling of API client Tiny networking: a minimal networking library by Chris Eidhof, read accompanying blog post
SUMMARY
SUMMARY NSURLSession is the main networking API (Sane) JSON parsing in Swift 2 requires third party libraries Popular third party networking libraries provide abstractions over NSURLSession
ADDITIONAL RESOURCES
ADDITIONAL RESOURCES NSURLSession Playground for this talk NSURLSession class reference NSURLSession Background Download URLSession programming guide Swift JSON Parsing by Example