SlideShare une entreprise Scribd logo
1  sur  33
Télécharger pour lire hors ligne
Luis Rei
LuisRei.com
me@luisrei.com
@lmrei
Developing
iOS
REST
Applications
• WHOAMI
• GLAZEDSOLUTIONS.COM
• HTML5 Mobile Apps - Friday 15h Main Stage
• It’s awesome: iPhone, iPad, iPod Touch
• Best Mobile App Dev Platform (by light years)
• Objective-C + Foundation + Cocoa
• Lots of potential users
• lots of potentially paying users
Why iOS
• Software architecture for distributed systems
• say web services/APIs
• Client-Server
• Works over HTTP & URI-based
• http://api.twitter.com/1/statuses/public_timeline.json
REST Quick Intro
• There’s always something you need in “the cloud”
• Data or processing power
• More true on mobile
• Universal: mobile, desktop, web clients
• It’s easy to implement server side ( at least the basic stuff)
• and everyone is doing it (twitter, github, amazon, google, ...)
• It’s easy to implement on the client
Why REST
REST/REST-Like APIs
iOS REST Recipe
Function Library I Use Currently iOS Boilerplate
HTTP Requests ASIHTTPRequest AFNetworking
JSON
SBJson
(AKA json-framework)
JSONkit
Image Caching
AFNetworking
(I previously used HJCache)
AFNetworking
Pull-To-Refresh
PullToRefreshTableViewController
by Leah Culver
EGOTableViewPullToRefresh
HUD
SVProgessHUD
(I previously used DSActivityView)
SVProgessHUD
• Am I connected to the internet?
• Wifi or Cellular?
Reachability
(SystemConfiguration framework)
NSString * const SRVR = @"api.example.com";
-(BOOL)reachable
{
    Reachability *r = [Reachability reachabilityWithHostName:SRVR];
    NetworkStatus internetStatus = [r currentReachabilityStatus];
    if(internetStatus == NotReachable) {
        return NO;
    }
    return YES;
}
NotReachable
ReachableViaWifi
ReachableViaWWAN
GET
- (void)makeGetRequest
{
NSURL *url = [NSURL URLWithString:@"http://api.example.com"];
ASIHTTPRequest *request =
[ASIHTTPRequest requestWithURL:url];
[request startSynchronous];
NSError *error = [request error];
if (!error && [request responseStatusCode] == 200)
{
NSString *response = [request responseString];
//NSData *responseData = [request responseData];
}
Errors
else if(error)
NSLog(@"request error: %@",[error localizedDescription]);
else if([request responseStatusCode] != 200)
NSLog(@"server says: %@", [request responseString]);
}
•The app continues to execute
•UI continues to be responsive
•The request runs in the background
•Two (common) ways of doing it in iOS:
•Delegate
•Block
Asynchronous Requests
• The delegator object has a delegate property that
points to the delegate object
• A delegate acts when its delegator encounters a
certain event
• The delegate adopts a protocol
• We’ll need 2 methods: success & failure
Cocoa Delegate Pattern
Asynchronous GET
- (void)makeGetRequest
{
NSURL *url = [NSURL URLWithString:@"http://allseeing-i.com"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDelegate:self];
[request startAsynchronous];
}
// DELEGATE METHODS:
- (void)requestFinished:(ASIHTTPRequest *)request
{
NSString *responseString = [request responseString];
}
- (void)requestFailed:(ASIHTTPRequest *)request
{
NSError *error = [request error];
}
Cocoa Blocks
• Ad hoc function body as an expression
• Carry their code & the data they need
• ideal for callbacks
• We’ll need 2 blocks: success & failure
Building Blocks
- (void)makeGetRequest
{
NSURL *url = [NSURL URLWithString:@"http://api.example.com"];
__block ASIHTTPRequest *request =
[ASIHTTPRequest requestWithURL:url];
[request setCompletionBlock:^{
NSString *responseString = [request responseString];
}];
[request setFailedBlock:^{
NSError *error = [request error];
}];
[request startAsynchronous];
}
SVProgressHUD
#import "SVProgressHUD.h"
- (void)makeGetRequest
{
NSURL *url = [NSURL URLWithString:@"http://api.example.com"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[SVProgressHUD showWithStatus:@"Fetching data"];
[request startSynchronous];
if (![request error])
{
" [SVProgressHUD dismissWithSuccess:@"Fetch Successful"];
...
}
else {
" [SVProgressHUD dismissWithError:@"Fetch Failed"];
...
}
}
Where to Load Data
• viewDidLoad / viewWillAppear
• Make the asynchronous request
• Show HUD or other “loading” indicators
• LOADED = NO;
• Delegate
• LOADED = YES;
• Reload table
• Partial Load + Pagination
• Load more at the end of the table
PullToRefresh
#import "PullRefreshTableViewController.h"
@interface MyTableViewController : PullRefreshTableViewController
- (void)refresh
{
  [self performSelector:@selector(add) withObject:nil afterDelay:2.0];
}
- (void) add
{
...
[self stopLoading];
}
.m
.h
Background Loading
& Caching Images
#import "UIImageView+AFNetworking.h"
NSURL *imageURL = [NSURL URLWithString:@”http://example.com/picture.jpg”];
UIImageView *image = [[UIImageView alloc] init];
[image setImageWithURL:imageURL];
Updating My Profile Picture
•Modify an existing record
•Authenticate
•Upload a file
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setRequestMethod:@"PUT"]; //REST modify using PUT
[request setPostFormat:ASIMultipartFormDataPostFormat];
// authentication
[request setUsername:username];
[request setPassword:password];
[request setFile:jpgPath forKey:@"image"];
"
[request startSynchronous];
POST & DELETE
[request setRequestMethod:@"POST"];
[request setRequestMethod:@"DELETE"];
I JSON (because it’s not XML)
JSON OBJECTIVE-C/FOUNDATION
Object NSDictionary
Array NSArray
String NSString
Number NSNumber
Boolean NSNumber (0 or 1)
1. Download a JSON string (via an http request)
2.Convert it to native data structures (parsing)
3.Use the native data structures
Parsing
[request startSynchronous];
...
SBJsonParser *prsr = [[[SBJsonParser alloc] init] autorelease];
// object
NSDictionary *data = [prsr objectWithString:[request responseString]];
// or Array
NSArray *data = [parsr objectWithString:[request responseString]];
INCEPTION
[{[{}]}]
An array of
objects with an
array of objects
[
	
  	
  	
  	
  {
	
  	
  	
  	
  	
  	
  	
  	
  "name":	
  "object1",
	
  	
  	
  	
  	
  	
  	
  	
  "sub":	
  [
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  {
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  "name":	
  "subobject1"
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  },
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  {
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  "name":	
  "subobject2"
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  }
	
  	
  	
  	
  	
  	
  	
  	
  ]
	
  	
  	
  	
  },
	
  	
  	
  
]
or rather JCEPTION
NSArray *jArray = [prsr objectWithString:data];
NSDictionary *obj1 = [jArray objectAtIndex:0];
NSString *obj1Name = [obj1 objectForKey:@”name”];
NSArray *obj1SubArray = [obj1 objectForKey:@”sub”];
NSDictionary *subObj1 = [obj1SubArray objectAtIndex:0];
NSNumber *subObj1Val = [subObj1 objectForKey@”value”];
[
	
  	
  	
  	
  {
	
  	
  	
  	
  	
  	
  	
  	
  "name":	
  "object1",
	
  	
  	
  	
  	
  	
  	
  	
  "sub":	
  [
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  {
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  "name":	
  "subobject1"
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  },
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  {
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  "value":	
  1
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  }
	
  	
  	
  	
  	
  	
  	
  	
  ]
	
  	
  	
  	
  },
]
...[[[prsr objectWithSring:data] objectAtIndex:0] objectForKey:@”sub]...
Developing iOS REST Applications

Contenu connexe

Tendances

HTML5 APIs - Where no man has gone before! - Altran
HTML5 APIs - Where no man has gone before! - AltranHTML5 APIs - Where no man has gone before! - Altran
HTML5 APIs - Where no man has gone before! - Altran
Robert Nyman
 
Tips and tricks for building api heavy ruby on rails applications
Tips and tricks for building api heavy ruby on rails applicationsTips and tricks for building api heavy ruby on rails applications
Tips and tricks for building api heavy ruby on rails applications
Tim Cull
 
JavaScript APIs - The Web is the Platform - MDN Hack Day - Buenos Aires
JavaScript APIs - The Web is the Platform - MDN Hack Day - Buenos AiresJavaScript APIs - The Web is the Platform - MDN Hack Day - Buenos Aires
JavaScript APIs - The Web is the Platform - MDN Hack Day - Buenos Aires
Robert Nyman
 

Tendances (20)

iOS5 NewStuff
iOS5 NewStuffiOS5 NewStuff
iOS5 NewStuff
 
JavaScript Promise
JavaScript PromiseJavaScript Promise
JavaScript Promise
 
How to write easy-to-test JavaScript
How to write easy-to-test JavaScriptHow to write easy-to-test JavaScript
How to write easy-to-test JavaScript
 
SenchaCon 2016: Ext JS + React: A Match Made in UX Heaven - Mark Brocato
SenchaCon 2016: Ext JS + React: A Match Made in UX Heaven - Mark BrocatoSenchaCon 2016: Ext JS + React: A Match Made in UX Heaven - Mark Brocato
SenchaCon 2016: Ext JS + React: A Match Made in UX Heaven - Mark Brocato
 
HTML5 APIs - Where no man has gone before! - Altran
HTML5 APIs - Where no man has gone before! - AltranHTML5 APIs - Where no man has gone before! - Altran
HTML5 APIs - Where no man has gone before! - Altran
 
Finally, Professional Frontend Dev with ReactJS, WebPack & Symfony (Symfony C...
Finally, Professional Frontend Dev with ReactJS, WebPack & Symfony (Symfony C...Finally, Professional Frontend Dev with ReactJS, WebPack & Symfony (Symfony C...
Finally, Professional Frontend Dev with ReactJS, WebPack & Symfony (Symfony C...
 
Webapps without the web
Webapps without the webWebapps without the web
Webapps without the web
 
REST/JSON/CoreData Example Code - A Tour
REST/JSON/CoreData Example Code - A TourREST/JSON/CoreData Example Code - A Tour
REST/JSON/CoreData Example Code - A Tour
 
OneRing @ OSCamp 2010
OneRing @ OSCamp 2010OneRing @ OSCamp 2010
OneRing @ OSCamp 2010
 
Promise pattern
Promise patternPromise pattern
Promise pattern
 
iPhone Appleless Apps
iPhone Appleless AppsiPhone Appleless Apps
iPhone Appleless Apps
 
 +  = ❤️ (Firebase for Apple Developers) at Swift Leeds
 +  = ❤️ (Firebase for Apple Developers) at Swift Leeds +  = ❤️ (Firebase for Apple Developers) at Swift Leeds
 +  = ❤️ (Firebase for Apple Developers) at Swift Leeds
 
jQuery in 15 minutes
jQuery in 15 minutesjQuery in 15 minutes
jQuery in 15 minutes
 
Django Celery - A distributed task queue
Django Celery - A distributed task queueDjango Celery - A distributed task queue
Django Celery - A distributed task queue
 
An Introduction to Celery
An Introduction to CeleryAn Introduction to Celery
An Introduction to Celery
 
New Design of OneRing
New Design of OneRingNew Design of OneRing
New Design of OneRing
 
Tips and tricks for building api heavy ruby on rails applications
Tips and tricks for building api heavy ruby on rails applicationsTips and tricks for building api heavy ruby on rails applications
Tips and tricks for building api heavy ruby on rails applications
 
Python Code Camp for Professionals 2/4
Python Code Camp for Professionals 2/4Python Code Camp for Professionals 2/4
Python Code Camp for Professionals 2/4
 
Behind the curtain - How Django handles a request
Behind the curtain - How Django handles a requestBehind the curtain - How Django handles a request
Behind the curtain - How Django handles a request
 
JavaScript APIs - The Web is the Platform - MDN Hack Day - Buenos Aires
JavaScript APIs - The Web is the Platform - MDN Hack Day - Buenos AiresJavaScript APIs - The Web is the Platform - MDN Hack Day - Buenos Aires
JavaScript APIs - The Web is the Platform - MDN Hack Day - Buenos Aires
 

Similaire à Developing iOS REST Applications

FI MUNI 2012 - iOS Basics
FI MUNI 2012 - iOS BasicsFI MUNI 2012 - iOS Basics
FI MUNI 2012 - iOS Basics
Petr Dvorak
 
Beginning icloud development - Cesare Rocchi - WhyMCA
Beginning icloud development - Cesare Rocchi - WhyMCABeginning icloud development - Cesare Rocchi - WhyMCA
Beginning icloud development - Cesare Rocchi - WhyMCA
Whymca
 
CouchDB on Android
CouchDB on AndroidCouchDB on Android
CouchDB on Android
Sven Haiges
 
Hızlı Cocoa Geliştirme (Develop your next cocoa app faster!)
Hızlı Cocoa Geliştirme (Develop your next cocoa app faster!)Hızlı Cocoa Geliştirme (Develop your next cocoa app faster!)
Hızlı Cocoa Geliştirme (Develop your next cocoa app faster!)
Sarp Erdag
 
iOS 2 - The practical Stuff
iOS 2 - The practical StuffiOS 2 - The practical Stuff
iOS 2 - The practical Stuff
Petr Dvorak
 
iOS App with Parse.com as RESTful Backend
iOS App with Parse.com as RESTful BackendiOS App with Parse.com as RESTful Backend
iOS App with Parse.com as RESTful Backend
Stefano Zanetti
 
Week 4 - jQuery + Ajax
Week 4 - jQuery + AjaxWeek 4 - jQuery + Ajax
Week 4 - jQuery + Ajax
baygross
 

Similaire à Developing iOS REST Applications (20)

Webエンジニアから見たiOS5
Webエンジニアから見たiOS5Webエンジニアから見たiOS5
Webエンジニアから見たiOS5
 
FI MUNI 2012 - iOS Basics
FI MUNI 2012 - iOS BasicsFI MUNI 2012 - iOS Basics
FI MUNI 2012 - iOS Basics
 
Parse London Meetup - Cloud Code Tips & Tricks
Parse London Meetup - Cloud Code Tips & TricksParse London Meetup - Cloud Code Tips & Tricks
Parse London Meetup - Cloud Code Tips & Tricks
 
MFF UK - Introduction to iOS
MFF UK - Introduction to iOSMFF UK - Introduction to iOS
MFF UK - Introduction to iOS
 
Beginning icloud development - Cesare Rocchi - WhyMCA
Beginning icloud development - Cesare Rocchi - WhyMCABeginning icloud development - Cesare Rocchi - WhyMCA
Beginning icloud development - Cesare Rocchi - WhyMCA
 
CouchDB on Android
CouchDB on AndroidCouchDB on Android
CouchDB on Android
 
Refresh Austin - Intro to Dexy
Refresh Austin - Intro to DexyRefresh Austin - Intro to Dexy
Refresh Austin - Intro to Dexy
 
Hızlı Cocoa Geliştirme (Develop your next cocoa app faster!)
Hızlı Cocoa Geliştirme (Develop your next cocoa app faster!)Hızlı Cocoa Geliştirme (Develop your next cocoa app faster!)
Hızlı Cocoa Geliştirme (Develop your next cocoa app faster!)
 
Leveraging parse.com for Speedy Development
Leveraging parse.com for Speedy DevelopmentLeveraging parse.com for Speedy Development
Leveraging parse.com for Speedy Development
 
第一次用Parse就深入淺出
第一次用Parse就深入淺出第一次用Parse就深入淺出
第一次用Parse就深入淺出
 
Javascript Everywhere
Javascript EverywhereJavascript Everywhere
Javascript Everywhere
 
iOS 2 - The practical Stuff
iOS 2 - The practical StuffiOS 2 - The practical Stuff
iOS 2 - The practical Stuff
 
iOS App with Parse.com as RESTful Backend
iOS App with Parse.com as RESTful BackendiOS App with Parse.com as RESTful Backend
iOS App with Parse.com as RESTful Backend
 
Moar tools for asynchrony!
Moar tools for asynchrony!Moar tools for asynchrony!
Moar tools for asynchrony!
 
UIWebView Tips
UIWebView TipsUIWebView Tips
UIWebView Tips
 
Desenvolvimento iOS - Aula 4
Desenvolvimento iOS - Aula 4Desenvolvimento iOS - Aula 4
Desenvolvimento iOS - Aula 4
 
iOS Beginners Lesson 4
iOS Beginners Lesson 4iOS Beginners Lesson 4
iOS Beginners Lesson 4
 
mobile in the cloud with diamonds. improved.
mobile in the cloud with diamonds. improved.mobile in the cloud with diamonds. improved.
mobile in the cloud with diamonds. improved.
 
Week 4 - jQuery + Ajax
Week 4 - jQuery + AjaxWeek 4 - jQuery + Ajax
Week 4 - jQuery + Ajax
 
What's Parse
What's ParseWhat's Parse
What's Parse
 

Dernier

Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
masabamasaba
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
VictoriaMetrics
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
masabamasaba
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
masabamasaba
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 

Dernier (20)

WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
 
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
WSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaSWSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaS
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
 
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
 

Developing iOS REST Applications

  • 2. • WHOAMI • GLAZEDSOLUTIONS.COM • HTML5 Mobile Apps - Friday 15h Main Stage
  • 3. • It’s awesome: iPhone, iPad, iPod Touch • Best Mobile App Dev Platform (by light years) • Objective-C + Foundation + Cocoa • Lots of potential users • lots of potentially paying users Why iOS
  • 4. • Software architecture for distributed systems • say web services/APIs • Client-Server • Works over HTTP & URI-based • http://api.twitter.com/1/statuses/public_timeline.json REST Quick Intro
  • 5. • There’s always something you need in “the cloud” • Data or processing power • More true on mobile • Universal: mobile, desktop, web clients • It’s easy to implement server side ( at least the basic stuff) • and everyone is doing it (twitter, github, amazon, google, ...) • It’s easy to implement on the client Why REST
  • 7. iOS REST Recipe Function Library I Use Currently iOS Boilerplate HTTP Requests ASIHTTPRequest AFNetworking JSON SBJson (AKA json-framework) JSONkit Image Caching AFNetworking (I previously used HJCache) AFNetworking Pull-To-Refresh PullToRefreshTableViewController by Leah Culver EGOTableViewPullToRefresh HUD SVProgessHUD (I previously used DSActivityView) SVProgessHUD
  • 8. • Am I connected to the internet? • Wifi or Cellular? Reachability (SystemConfiguration framework)
  • 9. NSString * const SRVR = @"api.example.com"; -(BOOL)reachable {     Reachability *r = [Reachability reachabilityWithHostName:SRVR];     NetworkStatus internetStatus = [r currentReachabilityStatus];     if(internetStatus == NotReachable) {         return NO;     }     return YES; } NotReachable ReachableViaWifi ReachableViaWWAN
  • 10. GET - (void)makeGetRequest { NSURL *url = [NSURL URLWithString:@"http://api.example.com"]; ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url]; [request startSynchronous]; NSError *error = [request error]; if (!error && [request responseStatusCode] == 200) { NSString *response = [request responseString]; //NSData *responseData = [request responseData]; }
  • 11. Errors else if(error) NSLog(@"request error: %@",[error localizedDescription]); else if([request responseStatusCode] != 200) NSLog(@"server says: %@", [request responseString]); }
  • 12. •The app continues to execute •UI continues to be responsive •The request runs in the background •Two (common) ways of doing it in iOS: •Delegate •Block Asynchronous Requests
  • 13. • The delegator object has a delegate property that points to the delegate object • A delegate acts when its delegator encounters a certain event • The delegate adopts a protocol • We’ll need 2 methods: success & failure Cocoa Delegate Pattern
  • 14. Asynchronous GET - (void)makeGetRequest { NSURL *url = [NSURL URLWithString:@"http://allseeing-i.com"]; ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url]; [request setDelegate:self]; [request startAsynchronous]; } // DELEGATE METHODS: - (void)requestFinished:(ASIHTTPRequest *)request { NSString *responseString = [request responseString]; } - (void)requestFailed:(ASIHTTPRequest *)request { NSError *error = [request error]; }
  • 15. Cocoa Blocks • Ad hoc function body as an expression • Carry their code & the data they need • ideal for callbacks • We’ll need 2 blocks: success & failure
  • 16. Building Blocks - (void)makeGetRequest { NSURL *url = [NSURL URLWithString:@"http://api.example.com"]; __block ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url]; [request setCompletionBlock:^{ NSString *responseString = [request responseString]; }]; [request setFailedBlock:^{ NSError *error = [request error]; }]; [request startAsynchronous]; }
  • 18. #import "SVProgressHUD.h" - (void)makeGetRequest { NSURL *url = [NSURL URLWithString:@"http://api.example.com"]; ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url]; [SVProgressHUD showWithStatus:@"Fetching data"]; [request startSynchronous]; if (![request error]) { " [SVProgressHUD dismissWithSuccess:@"Fetch Successful"]; ... } else { " [SVProgressHUD dismissWithError:@"Fetch Failed"]; ... } }
  • 19. Where to Load Data • viewDidLoad / viewWillAppear • Make the asynchronous request • Show HUD or other “loading” indicators • LOADED = NO; • Delegate • LOADED = YES; • Reload table • Partial Load + Pagination • Load more at the end of the table
  • 21.
  • 22. #import "PullRefreshTableViewController.h" @interface MyTableViewController : PullRefreshTableViewController - (void)refresh {   [self performSelector:@selector(add) withObject:nil afterDelay:2.0]; } - (void) add { ... [self stopLoading]; } .m .h
  • 24. #import "UIImageView+AFNetworking.h" NSURL *imageURL = [NSURL URLWithString:@”http://example.com/picture.jpg”]; UIImageView *image = [[UIImageView alloc] init]; [image setImageWithURL:imageURL];
  • 25. Updating My Profile Picture •Modify an existing record •Authenticate •Upload a file
  • 26. ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url]; [request setRequestMethod:@"PUT"]; //REST modify using PUT [request setPostFormat:ASIMultipartFormDataPostFormat]; // authentication [request setUsername:username]; [request setPassword:password]; [request setFile:jpgPath forKey:@"image"]; " [request startSynchronous];
  • 27. POST & DELETE [request setRequestMethod:@"POST"]; [request setRequestMethod:@"DELETE"];
  • 28. I JSON (because it’s not XML) JSON OBJECTIVE-C/FOUNDATION Object NSDictionary Array NSArray String NSString Number NSNumber Boolean NSNumber (0 or 1)
  • 29. 1. Download a JSON string (via an http request) 2.Convert it to native data structures (parsing) 3.Use the native data structures
  • 30. Parsing [request startSynchronous]; ... SBJsonParser *prsr = [[[SBJsonParser alloc] init] autorelease]; // object NSDictionary *data = [prsr objectWithString:[request responseString]]; // or Array NSArray *data = [parsr objectWithString:[request responseString]];
  • 31. INCEPTION [{[{}]}] An array of objects with an array of objects [        {                "name":  "object1",                "sub":  [                        {                                "name":  "subobject1"                        },                        {                                "name":  "subobject2"                        }                ]        },       ] or rather JCEPTION
  • 32. NSArray *jArray = [prsr objectWithString:data]; NSDictionary *obj1 = [jArray objectAtIndex:0]; NSString *obj1Name = [obj1 objectForKey:@”name”]; NSArray *obj1SubArray = [obj1 objectForKey:@”sub”]; NSDictionary *subObj1 = [obj1SubArray objectAtIndex:0]; NSNumber *subObj1Val = [subObj1 objectForKey@”value”]; [        {                "name":  "object1",                "sub":  [                        {                                "name":  "subobject1"                        },                        {                                "value":  1                        }                ]        }, ] ...[[[prsr objectWithSring:data] objectAtIndex:0] objectForKey:@”sub]...