SlideShare a Scribd company logo
CLIENT SERVER
COMMUNICATION
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
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
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: Efficient 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" <~~ 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
])
}
}
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
different 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

More Related Content

What's hot

Data Binding in Silverlight
Data Binding in SilverlightData Binding in Silverlight
Data Binding in Silverlight
Boulos Dib
 
Entity Framework Database and Code First
Entity Framework Database and Code FirstEntity Framework Database and Code First
Entity Framework Database and Code First
James Johnson
 
Spring data jpa
Spring data jpaSpring data jpa
Spring data jpa
Jeevesh Pandey
 
Connecting to a REST API in iOS
Connecting to a REST API in iOSConnecting to a REST API in iOS
Connecting to a REST API in iOS
gillygize
 
FITC presents: Mobile & offline data synchronization in Angular JS
FITC presents: Mobile & offline data synchronization in Angular JSFITC presents: Mobile & offline data synchronization in Angular JS
FITC presents: Mobile & offline data synchronization in Angular JS
FITC
 
High Performance Core Data
High Performance Core DataHigh Performance Core Data
High Performance Core Data
Matthew Morey
 
Paris Tech Meetup talk : Troubles start at version 1.0
Paris Tech Meetup talk : Troubles start at version 1.0Paris Tech Meetup talk : Troubles start at version 1.0
Paris Tech Meetup talk : Troubles start at version 1.0
Laurent Cerveau
 
Oak Lucene Indexes
Oak Lucene IndexesOak Lucene Indexes
Oak Lucene Indexes
Chetan Mehrotra
 
SquiDB: a SQLite layer for Android - Jonathan Koren, Yahoo!
SquiDB: a SQLite layer for Android - Jonathan Koren, Yahoo!SquiDB: a SQLite layer for Android - Jonathan Koren, Yahoo!
SquiDB: a SQLite layer for Android - Jonathan Koren, Yahoo!
DroidConTLV
 
Hibernate Basic Concepts - Presentation
Hibernate Basic Concepts - PresentationHibernate Basic Concepts - Presentation
Hibernate Basic Concepts - Presentation
Khoa Nguyen
 
Adventures in Multithreaded Core Data
Adventures in Multithreaded Core DataAdventures in Multithreaded Core Data
Adventures in Multithreaded Core DataInferis
 
Create a Core Data Observer in 10mins
Create a Core Data Observer in 10minsCreate a Core Data Observer in 10mins
Create a Core Data Observer in 10mins
zmcartor
 
Json
Json Json
Using Webservice in iOS
Using Webservice  in iOS Using Webservice  in iOS
Using Webservice in iOS
Mahboob Nur
 
Euruko 2009 - DataObjects
Euruko 2009 - DataObjectsEuruko 2009 - DataObjects
Euruko 2009 - DataObjects
Dirkjan Bussink
 
iOSDevCamp 2011 Core Data
iOSDevCamp 2011 Core DataiOSDevCamp 2011 Core Data
iOSDevCamp 2011 Core Data
Chris Mar
 
Dicoding Developer Coaching #19: Android | Menyimpan Database Secara Local di...
Dicoding Developer Coaching #19: Android | Menyimpan Database Secara Local di...Dicoding Developer Coaching #19: Android | Menyimpan Database Secara Local di...
Dicoding Developer Coaching #19: Android | Menyimpan Database Secara Local di...
DicodingEvent
 

What's hot (20)

Data Binding in Silverlight
Data Binding in SilverlightData Binding in Silverlight
Data Binding in Silverlight
 
Entity Framework Database and Code First
Entity Framework Database and Code FirstEntity Framework Database and Code First
Entity Framework Database and Code First
 
Spring data jpa
Spring data jpaSpring data jpa
Spring data jpa
 
Connecting to a REST API in iOS
Connecting to a REST API in iOSConnecting to a REST API in iOS
Connecting to a REST API in iOS
 
FITC presents: Mobile & offline data synchronization in Angular JS
FITC presents: Mobile & offline data synchronization in Angular JSFITC presents: Mobile & offline data synchronization in Angular JS
FITC presents: Mobile & offline data synchronization in Angular JS
 
High Performance Core Data
High Performance Core DataHigh Performance Core Data
High Performance Core Data
 
Paris Tech Meetup talk : Troubles start at version 1.0
Paris Tech Meetup talk : Troubles start at version 1.0Paris Tech Meetup talk : Troubles start at version 1.0
Paris Tech Meetup talk : Troubles start at version 1.0
 
Oak Lucene Indexes
Oak Lucene IndexesOak Lucene Indexes
Oak Lucene Indexes
 
SquiDB: a SQLite layer for Android - Jonathan Koren, Yahoo!
SquiDB: a SQLite layer for Android - Jonathan Koren, Yahoo!SquiDB: a SQLite layer for Android - Jonathan Koren, Yahoo!
SquiDB: a SQLite layer for Android - Jonathan Koren, Yahoo!
 
Hibernate Basic Concepts - Presentation
Hibernate Basic Concepts - PresentationHibernate Basic Concepts - Presentation
Hibernate Basic Concepts - Presentation
 
Adventures in Multithreaded Core Data
Adventures in Multithreaded Core DataAdventures in Multithreaded Core Data
Adventures in Multithreaded Core Data
 
Create a Core Data Observer in 10mins
Create a Core Data Observer in 10minsCreate a Core Data Observer in 10mins
Create a Core Data Observer in 10mins
 
Json
Json Json
Json
 
Using Webservice in iOS
Using Webservice  in iOS Using Webservice  in iOS
Using Webservice in iOS
 
Ajax
AjaxAjax
Ajax
 
Spring Data in 10 minutes
Spring Data in 10 minutesSpring Data in 10 minutes
Spring Data in 10 minutes
 
Euruko 2009 - DataObjects
Euruko 2009 - DataObjectsEuruko 2009 - DataObjects
Euruko 2009 - DataObjects
 
Simple Data Binding
Simple Data BindingSimple Data Binding
Simple Data Binding
 
iOSDevCamp 2011 Core Data
iOSDevCamp 2011 Core DataiOSDevCamp 2011 Core Data
iOSDevCamp 2011 Core Data
 
Dicoding Developer Coaching #19: Android | Menyimpan Database Secara Local di...
Dicoding Developer Coaching #19: Android | Menyimpan Database Secara Local di...Dicoding Developer Coaching #19: Android | Menyimpan Database Secara Local di...
Dicoding Developer Coaching #19: Android | Menyimpan Database Secara Local di...
 

Viewers also liked

Make School 2017 - Mastering iOS Development
Make School 2017 - Mastering iOS DevelopmentMake School 2017 - Mastering iOS Development
Make School 2017 - Mastering iOS Development
Make School
 
Swift Objective-C Interop
Swift Objective-C InteropSwift Objective-C Interop
Swift Objective-C Interop
Make School
 
Xcode Project Infrastructure
Xcode Project InfrastructureXcode Project Infrastructure
Xcode Project Infrastructure
Make School
 
Dependency Management on iOS
Dependency Management on iOSDependency Management on iOS
Dependency Management on iOS
Make School
 
Swift 2 intro
Swift 2 introSwift 2 intro
Swift 2 intro
Make School
 
Client Server Synchronization iOS
Client Server Synchronization iOSClient Server Synchronization iOS
Client Server Synchronization iOS
Make School
 
Standard libraries on iOS
Standard libraries on iOSStandard libraries on iOS
Standard libraries on iOS
Make School
 
Localization and Accessibility on iOS
Localization and Accessibility on iOSLocalization and Accessibility on iOS
Localization and Accessibility on iOS
Make School
 
Error Handling in Swift
Error Handling in SwiftError Handling in Swift
Error Handling in Swift
Make School
 
Layout with Stack View, Table View, and Collection View
Layout with Stack View, Table View, and Collection ViewLayout with Stack View, Table View, and Collection View
Layout with Stack View, Table View, and Collection View
Make School
 
Memory Management on iOS
Memory Management on iOSMemory Management on iOS
Memory Management on iOS
Make School
 
Intro to iOS Application Architecture
Intro to iOS Application ArchitectureIntro to iOS Application Architecture
Intro to iOS Application Architecture
Make School
 
Distributing information on iOS
Distributing information on iOSDistributing information on iOS
Distributing information on iOS
Make School
 
iOS Layout Overview
iOS Layout OverviewiOS Layout Overview
iOS Layout Overview
Make School
 
Building a Backend with Flask
Building a Backend with FlaskBuilding a Backend with Flask
Building a Backend with Flask
Make School
 
Client Server Security with Flask and iOS
Client Server Security with Flask and iOSClient Server Security with Flask and iOS
Client Server Security with Flask and iOS
Make School
 
Automated Testing on iOS
Automated Testing on iOSAutomated Testing on iOS
Automated Testing on iOS
Make School
 
How to build quality software
How to build quality softwareHow to build quality software
How to build quality software
Make School
 

Viewers also liked (18)

Make School 2017 - Mastering iOS Development
Make School 2017 - Mastering iOS DevelopmentMake School 2017 - Mastering iOS Development
Make School 2017 - Mastering iOS Development
 
Swift Objective-C Interop
Swift Objective-C InteropSwift Objective-C Interop
Swift Objective-C Interop
 
Xcode Project Infrastructure
Xcode Project InfrastructureXcode Project Infrastructure
Xcode Project Infrastructure
 
Dependency Management on iOS
Dependency Management on iOSDependency Management on iOS
Dependency Management on iOS
 
Swift 2 intro
Swift 2 introSwift 2 intro
Swift 2 intro
 
Client Server Synchronization iOS
Client Server Synchronization iOSClient Server Synchronization iOS
Client Server Synchronization iOS
 
Standard libraries on iOS
Standard libraries on iOSStandard libraries on iOS
Standard libraries on iOS
 
Localization and Accessibility on iOS
Localization and Accessibility on iOSLocalization and Accessibility on iOS
Localization and Accessibility on iOS
 
Error Handling in Swift
Error Handling in SwiftError Handling in Swift
Error Handling in Swift
 
Layout with Stack View, Table View, and Collection View
Layout with Stack View, Table View, and Collection ViewLayout with Stack View, Table View, and Collection View
Layout with Stack View, Table View, and Collection View
 
Memory Management on iOS
Memory Management on iOSMemory Management on iOS
Memory Management on iOS
 
Intro to iOS Application Architecture
Intro to iOS Application ArchitectureIntro to iOS Application Architecture
Intro to iOS Application Architecture
 
Distributing information on iOS
Distributing information on iOSDistributing information on iOS
Distributing information on iOS
 
iOS Layout Overview
iOS Layout OverviewiOS Layout Overview
iOS Layout Overview
 
Building a Backend with Flask
Building a Backend with FlaskBuilding a Backend with Flask
Building a Backend with Flask
 
Client Server Security with Flask and iOS
Client Server Security with Flask and iOSClient Server Security with Flask and iOS
Client Server Security with Flask and iOS
 
Automated Testing on iOS
Automated Testing on iOSAutomated Testing on iOS
Automated Testing on iOS
 
How to build quality software
How to build quality softwareHow to build quality software
How to build quality software
 

Similar to Client Server Communication on iOS

SwiftyJSON 慘痛經驗
SwiftyJSON   慘痛經驗SwiftyJSON   慘痛經驗
SwiftyJSON 慘痛經驗
Hokila Jan
 
Taming Core Data by Arek Holko, Macoscope
Taming Core Data by Arek Holko, MacoscopeTaming Core Data by Arek Holko, Macoscope
Taming Core Data by Arek Holko, Macoscope
Macoscope
 
JSON Fuzzing: New approach to old problems
JSON Fuzzing: New  approach to old problemsJSON Fuzzing: New  approach to old problems
JSON Fuzzing: New approach to old problemstitanlambda
 
Managing parallelism using coroutines
Managing parallelism using coroutinesManaging parallelism using coroutines
Managing parallelism using coroutines
Fabio Collini
 
Modern Networking with Swish
Modern Networking with SwishModern Networking with Swish
Modern Networking with Swish
jakecraige
 
Apache Utilities At Work V5
Apache Utilities At Work   V5Apache Utilities At Work   V5
Apache Utilities At Work V5
Tom Marrs
 
Json tutorial, a beguiner guide
Json tutorial, a beguiner guideJson tutorial, a beguiner guide
Json tutorial, a beguiner guide
Rafael Montesinos Muñoz
 
Java7 New Features and Code Examples
Java7 New Features and Code ExamplesJava7 New Features and Code Examples
Java7 New Features and Code Examples
Naresh Chintalcheru
 
Basics of JSON (JavaScript Object Notation) with examples
Basics of JSON (JavaScript Object Notation) with examplesBasics of JSON (JavaScript Object Notation) with examples
Basics of JSON (JavaScript Object Notation) with examples
Sanjeev Kumar Jaiswal
 
Denys Serhiienko "ASGI in depth"
Denys Serhiienko "ASGI in depth"Denys Serhiienko "ASGI in depth"
Denys Serhiienko "ASGI in depth"
Fwdays
 
PostgreSQL's Secret NoSQL Superpowers
PostgreSQL's Secret NoSQL SuperpowersPostgreSQL's Secret NoSQL Superpowers
PostgreSQL's Secret NoSQL Superpowers
Amanda Gilmore
 
Overview of RESTful web services
Overview of RESTful web servicesOverview of RESTful web services
Overview of RESTful web services
nbuddharaju
 
CouchDB on Android
CouchDB on AndroidCouchDB on Android
CouchDB on AndroidSven Haiges
 
RESTFul development with Apache sling
RESTFul development with Apache slingRESTFul development with Apache sling
RESTFul development with Apache sling
Sergii Fesenko
 
Developing RESTful WebServices using Jersey
Developing RESTful WebServices using JerseyDeveloping RESTful WebServices using Jersey
Developing RESTful WebServices using Jerseyb_kathir
 
Xml & Java
Xml & JavaXml & Java
Xml & Java
Slim Ouertani
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotation
javatwo2011
 
JavaScript Lessons 2023 V2
JavaScript Lessons 2023 V2JavaScript Lessons 2023 V2
JavaScript Lessons 2023 V2
Laurence Svekis ✔
 
[@IndeedEng] Building Indeed Resume Search
[@IndeedEng] Building Indeed Resume Search[@IndeedEng] Building Indeed Resume Search
[@IndeedEng] Building Indeed Resume Search
indeedeng
 

Similar to Client Server Communication on iOS (20)

SwiftyJSON 慘痛經驗
SwiftyJSON   慘痛經驗SwiftyJSON   慘痛經驗
SwiftyJSON 慘痛經驗
 
Taming Core Data by Arek Holko, Macoscope
Taming Core Data by Arek Holko, MacoscopeTaming Core Data by Arek Holko, Macoscope
Taming Core Data by Arek Holko, Macoscope
 
JSON Fuzzing: New approach to old problems
JSON Fuzzing: New  approach to old problemsJSON Fuzzing: New  approach to old problems
JSON Fuzzing: New approach to old problems
 
Managing parallelism using coroutines
Managing parallelism using coroutinesManaging parallelism using coroutines
Managing parallelism using coroutines
 
Modern Networking with Swish
Modern Networking with SwishModern Networking with Swish
Modern Networking with Swish
 
Apache Utilities At Work V5
Apache Utilities At Work   V5Apache Utilities At Work   V5
Apache Utilities At Work V5
 
Json tutorial, a beguiner guide
Json tutorial, a beguiner guideJson tutorial, a beguiner guide
Json tutorial, a beguiner guide
 
Java7 New Features and Code Examples
Java7 New Features and Code ExamplesJava7 New Features and Code Examples
Java7 New Features and Code Examples
 
Basics of JSON (JavaScript Object Notation) with examples
Basics of JSON (JavaScript Object Notation) with examplesBasics of JSON (JavaScript Object Notation) with examples
Basics of JSON (JavaScript Object Notation) with examples
 
droidparts
droidpartsdroidparts
droidparts
 
Denys Serhiienko "ASGI in depth"
Denys Serhiienko "ASGI in depth"Denys Serhiienko "ASGI in depth"
Denys Serhiienko "ASGI in depth"
 
PostgreSQL's Secret NoSQL Superpowers
PostgreSQL's Secret NoSQL SuperpowersPostgreSQL's Secret NoSQL Superpowers
PostgreSQL's Secret NoSQL Superpowers
 
Overview of RESTful web services
Overview of RESTful web servicesOverview of RESTful web services
Overview of RESTful web services
 
CouchDB on Android
CouchDB on AndroidCouchDB on Android
CouchDB on Android
 
RESTFul development with Apache sling
RESTFul development with Apache slingRESTFul development with Apache sling
RESTFul development with Apache sling
 
Developing RESTful WebServices using Jersey
Developing RESTful WebServices using JerseyDeveloping RESTful WebServices using Jersey
Developing RESTful WebServices using Jersey
 
Xml & Java
Xml & JavaXml & Java
Xml & Java
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotation
 
JavaScript Lessons 2023 V2
JavaScript Lessons 2023 V2JavaScript Lessons 2023 V2
JavaScript Lessons 2023 V2
 
[@IndeedEng] Building Indeed Resume Search
[@IndeedEng] Building Indeed Resume Search[@IndeedEng] Building Indeed Resume Search
[@IndeedEng] Building Indeed Resume Search
 

Recently uploaded

Strategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptxStrategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptx
varshanayak241
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
Matt Welsh
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
IES VE
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
Ortus Solutions, Corp
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
WSO2
 
Advanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should KnowAdvanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should Know
Peter Caitens
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
Paco van Beckhoven
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Globus
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar
 
Visitor Management System in India- Vizman.app
Visitor Management System in India- Vizman.appVisitor Management System in India- Vizman.app
Visitor Management System in India- Vizman.app
NaapbooksPrivateLimi
 
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Hivelance Technology
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
Globus
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
Ortus Solutions, Corp
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
abdulrafaychaudhry
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
informapgpstrackings
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
Tier1 app
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Globus
 
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
XfilesPro
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Anthony Dahanne
 
Explore Modern SharePoint Templates for 2024
Explore Modern SharePoint Templates for 2024Explore Modern SharePoint Templates for 2024
Explore Modern SharePoint Templates for 2024
Sharepoint Designs
 

Recently uploaded (20)

Strategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptxStrategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptx
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
 
Advanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should KnowAdvanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should Know
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
 
Visitor Management System in India- Vizman.app
Visitor Management System in India- Vizman.appVisitor Management System in India- Vizman.app
Visitor Management System in India- Vizman.app
 
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
 
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
 
Explore Modern SharePoint Templates for 2024
Explore Modern SharePoint Templates for 2024Explore Modern SharePoint Templates for 2024
Explore Modern SharePoint Templates for 2024
 

Client Server Communication on iOS

  • 1.
  • 5. NSURLSESSION Class provided by Foundation library that allows issuing HTTP requests
  • 6. 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()
  • 7. 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
  • 8. 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
  • 9. 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()
  • 11. HANDLING JSON Foundation framework provides NSJSONSerialization Class is poorly suited for Swift 😢
  • 12. 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
  • 13. 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.
  • 14. HANDLING JSON WITH GLOSSY - 1 struct 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 ]) } }
  • 15. 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()
  • 17. 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)
  • 18. 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
  • 20. 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
  • 22. ADDITIONAL RESOURCES NSURLSession Playground for this talk NSURLSession class reference NSURLSession Background Download URLSession programming guide Swift JSON Parsing by Example