CLIENT SERVER COMMUNICATION · Source: Efficient JSON in Swift with Functional Concepts and...

22

Transcript of CLIENT SERVER COMMUNICATION · Source: Efficient JSON in Swift with Functional Concepts and...

Page 1: CLIENT SERVER COMMUNICATION · Source: Efficient JSON in Swift with Functional Concepts and Generics. HANDLING JSON For sane JSON parsing code we need to use third party libraries
Page 2: CLIENT SERVER COMMUNICATION · Source: Efficient JSON in Swift with Functional Concepts and Generics. HANDLING JSON For sane JSON parsing code we need to use third party libraries

CLIENT SERVER COMMUNICATION

Page 3: CLIENT SERVER COMMUNICATION · Source: Efficient JSON in Swift with Functional Concepts and Generics. HANDLING JSON For sane JSON parsing code we need to use third party libraries

AGENDA

NSURLSession

Handling JSON

Third party networking libraries

Page 4: CLIENT SERVER COMMUNICATION · Source: Efficient JSON in Swift with Functional Concepts and Generics. HANDLING JSON For sane JSON parsing code we need to use third party libraries

NSURLSESSION

Page 5: CLIENT SERVER COMMUNICATION · Source: Efficient JSON in Swift with Functional Concepts and Generics. HANDLING JSON For sane JSON parsing code we need to use third party libraries

NSURLSESSION

Class provided by Foundation library that allows

issuing HTTP requests

Page 6: CLIENT SERVER COMMUNICATION · Source: Efficient JSON in Swift with Functional Concepts and Generics. HANDLING JSON For sane JSON parsing code we need to use third party libraries

CANONICAL EXAMPLElet 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()

Page 7: CLIENT SERVER COMMUNICATION · Source: Efficient JSON in Swift with Functional Concepts and Generics. HANDLING JSON For sane JSON parsing code we need to use third party libraries

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

Page 8: CLIENT SERVER COMMUNICATION · Source: Efficient JSON in Swift with Functional Concepts and Generics. HANDLING JSON For sane JSON parsing code we need to use third party libraries

NSURLSESSION - TASK TYPES

NSURLSessionDataTask: A task for retrieving the contents

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

Background compatible

Not background compatible!

Source: NSURLSession reference

Page 9: CLIENT SERVER COMMUNICATION · Source: Efficient JSON in Swift with Functional Concepts and Generics. HANDLING JSON For sane JSON parsing code we need to use third party libraries

POST EXAMPLElet 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()

Page 10: CLIENT SERVER COMMUNICATION · Source: Efficient JSON in Swift with Functional Concepts and Generics. HANDLING JSON For sane JSON parsing code we need to use third party libraries

HANDLING JSON

Page 11: CLIENT SERVER COMMUNICATION · Source: Efficient JSON in Swift with Functional Concepts and Generics. HANDLING JSON For sane JSON parsing code we need to use third party libraries

HANDLING JSON

Foundation framework provides NSJSONSerialization

Class is poorly suited for Swift 😢

Page 12: CLIENT SERVER COMMUNICATION · Source: Efficient JSON in Swift with Functional Concepts and Generics. HANDLING JSON For sane JSON parsing code we need to use third party libraries

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: Efficient JSON in Swift with Functional Concepts and Generics

Page 13: CLIENT SERVER COMMUNICATION · Source: Efficient JSON in Swift with Functional Concepts and Generics. HANDLING JSON For sane JSON parsing code we need to use third party libraries

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.

Page 14: CLIENT SERVER COMMUNICATION · Source: Efficient JSON in Swift with Functional Concepts and Generics. HANDLING JSON For sane JSON parsing code we need to use third party libraries

HANDLING JSON WITH GLOSSY - 1struct Post: Glossy { var title: String? var content: String? init?(json: JSON) { self.title = "title" <~~ json self.content = "content" <~~ json } init(title: String, content: String) { self.title = title self.content = content } func toJSON() -> JSON? { return jsonify([ "title" ~~> self.title, "content" ~~> self.content ]) }}

Page 15: CLIENT SERVER COMMUNICATION · Source: Efficient JSON in Swift with Functional Concepts and Generics. HANDLING JSON For sane JSON parsing code we need to use third party libraries

HANDLING JSON WITH GLOSSY - 2let 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 = jsonDataurlRequestPost.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()

Page 16: CLIENT SERVER COMMUNICATION · Source: Efficient JSON in Swift with Functional Concepts and Generics. HANDLING JSON For sane JSON parsing code we need to use third party libraries

THIRD PARTY NETWORKING LIBRARIES

Page 17: CLIENT SERVER COMMUNICATION · Source: Efficient JSON in Swift with Functional Concepts and Generics. HANDLING JSON For sane JSON parsing code we need to use third party libraries

THIRD PARTY NETWORKING

Networking code encounters issues that are similar for all different kinds of apps

Third party libraries help in solving these common problems (e.g. parsing responses from as server)

Page 18: CLIENT SERVER COMMUNICATION · Source: Efficient JSON in Swift with Functional Concepts and Generics. HANDLING JSON For sane JSON parsing code we need to use third party libraries

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

Page 19: CLIENT SERVER COMMUNICATION · Source: Efficient JSON in Swift with Functional Concepts and Generics. HANDLING JSON For sane JSON parsing code we need to use third party libraries

SUMMARY

Page 20: CLIENT SERVER COMMUNICATION · Source: Efficient JSON in Swift with Functional Concepts and Generics. HANDLING JSON For sane JSON parsing code we need to use third party libraries

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

Page 21: CLIENT SERVER COMMUNICATION · Source: Efficient JSON in Swift with Functional Concepts and Generics. HANDLING JSON For sane JSON parsing code we need to use third party libraries

ADDITIONAL RESOURCES