Top Banner
Luis Rei LuisRei.com [email protected] @lmrei Developing iOS REST Applications
33

Developing iOS REST Applications

Oct 12, 2014

Download

Documents

Luis Rei

Talk at Codebits 2011
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 2: Developing iOS REST Applications

• WHOAMI

• GLAZEDSOLUTIONS.COM

• HTML5 Mobile Apps - Friday 15h Main Stage

Page 3: Developing iOS REST Applications

• 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

Page 4: Developing iOS REST Applications

• 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

Page 5: Developing iOS REST Applications

• 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

Page 6: Developing iOS REST Applications

REST/REST-Like APIs

Page 7: Developing iOS REST Applications

iOS REST RecipeFunction 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 PullToRefreshTableViewControllerby Leah Culver EGOTableViewPullToRefresh

HUD SVProgessHUD(I previously used DSActivityView) SVProgessHUD

Page 8: Developing iOS REST Applications

• Am I connected to the internet?

• Wifi or Cellular?

Reachability(SystemConfiguration framework)

Page 9: Developing iOS REST Applications

NSString * const SRVR = @"api.example.com";

-(BOOL)reachable{    Reachability *r = [Reachability reachabilityWithHostName:SRVR];

    NetworkStatus internetStatus = [r currentReachabilityStatus];

    if(internetStatus == NotReachable) {        return NO;    }    return YES;}

NotReachableReachableViaWifi

ReachableViaWWAN

Page 10: Developing iOS REST Applications

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]; }

Page 11: Developing iOS REST Applications

Errors

else if(error)NSLog(@"request error: %@",[error localizedDescription]);

else if([request responseStatusCode] != 200)NSLog(@"server says: %@", [request responseString]);

}

Page 12: Developing iOS REST Applications

•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

Page 13: Developing iOS REST Applications

• 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

Page 14: Developing iOS REST Applications

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];}

Page 15: Developing iOS REST Applications

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

Page 16: Developing iOS REST Applications

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];}

Page 17: Developing iOS REST Applications

SVProgressHUD

Page 18: Developing iOS REST Applications

#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"];

... }}

Page 19: Developing iOS REST Applications

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

Page 20: Developing iOS REST Applications

PullToRefresh

Page 21: Developing iOS REST Applications
Page 22: Developing iOS REST Applications

#import "PullRefreshTableViewController.h"

@interface MyTableViewController : PullRefreshTableViewController

- (void)refresh {  [self performSelector:@selector(add) withObject:nil afterDelay:2.0];}

- (void) add {...[self stopLoading];

}

.m

.h

Page 23: Developing iOS REST Applications

Background Loading & Caching Images

Page 24: Developing iOS REST Applications

#import "UIImageView+AFNetworking.h"

NSURL *imageURL = [NSURL URLWithString:@”http://example.com/picture.jpg”];UIImageView *image = [[UIImageView alloc] init];

[image setImageWithURL:imageURL];

Page 25: Developing iOS REST Applications

Updating My Profile Picture

•Modify an existing record

•Authenticate

•Upload a file

Page 26: Developing iOS REST Applications

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];

Page 27: Developing iOS REST Applications

POST & DELETE

[request setRequestMethod:@"POST"];

[request setRequestMethod:@"DELETE"];

Page 28: Developing iOS REST Applications

I JSON (because it’s not XML)

JSON OBJECTIVE-C/FOUNDATION

Object NSDictionary

Array NSArray

String NSString

Number NSNumber

Boolean NSNumber (0 or 1)

Page 29: Developing iOS REST Applications

1. Download a JSON string (via an http request)

2.Convert it to native data structures (parsing)

3.Use the native data structures

Page 30: Developing iOS REST Applications

Parsing

[request startSynchronous];...SBJsonParser *prsr = [[[SBJsonParser alloc] init] autorelease];

// objectNSDictionary *data = [prsr objectWithString:[request responseString]];

// or ArrayNSArray *data = [parsr objectWithString:[request responseString]];

Page 31: Developing iOS REST Applications

INCEPTION

[{[{}]}]An array of

objects with an array of objects

[        {                "name":  "object1",                "sub":  [                        {                                "name":  "subobject1"                        },                        {                                "name":  "subobject2"                        }                ]        },      ]

or rather JCEPTION

Page 32: Developing iOS REST Applications

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]...

Page 33: Developing iOS REST Applications