SlideShare a Scribd company logo
1 of 32
RESTful iOS with RestKit

             Taras Kalapun
              Sergey Kluev
What is RestKit?




                   2
3
4
RestKit Architecture
        • Network Layer

        • Object Mapping

        • Core Data

        • Pluggable parsing layer

        • Integration Points

                                    5
Network Layer




                6
Key Concepts
• RKClient - Your user agent
• Base URLs and Resource Paths
• RKRequest & RKResponse - The HTTP
  lifecycle
• RKRequestQueue - A lightweight queue
  implementation
• RKParams - Multi-part MIME requests
• Reachability - Detecting offline/online status
                                                   7
RKClient
• Sending Asynchronous Requests
1   – get:delegate:
2   – get:queryParams:delegate:
3   – post:params:delegate:
4   – put:params:delegate:
5   – delete:delegate:




                                  8
Initializing RKClient

- (void)initRKClient {
! // Initialize with a Base URL
! RKClient* client = [RKClient clientWithBaseURL:@"http://restkit.org"];
!
! // Setup HTTP AUTH
! client.username = @"restkit";
! client.password = @"rocks";
!
! // Set an app-wide API key HTTP header
! [client setValue:@"123456" forHTTPHeaderField:@"X-RESTKIT-API-KEY"];
!
! // The first initialized RKClient becomes
! // the sharedClient instance
! [[RKClient sharedClient] isNetworkAvailable];
}




                                                                           9
Sending Requests
- (void)sendRequest {
! // Send an HTTP GET request to 'http://restkit.org/contacts'
! [[RKClient sharedClient] get:@"/contacts" delegate:self];
}

// RKRequestDelegate methods

- (void)request:(RKRequest*)request didLoadResponse:(RKResponse*)response {
! NSLog(@"Yay! We Got a response");
}

- (void)request:(RKRequest*)request didFailLoadWithError:(NSError*)error {
! NSLog(@"Oh no! Error: %@", [error localizedDescription]);
}




                                                                         10
Processing Responses
- (void)sendRequest {
! // Send an HTTP GET request to 'http://restkit.org/contacts'
! [[RKClient sharedClient] get:@"/contacts" delegate:self];
}

- (void)request:(RKRequest*)request didLoadResponse:(RKResponse*)response
{
! NSLog(@"Request Headers: %@", [response allHeaderFields]);
! NSLog(@"Cookies: %@", [response cookies])
!
! if ([response isSuccessful]) {
! !      // Response status was 200..299
! !      if ([response isCreated] && [response isJSON]) {
! !      !   // Looks like we have a 201 response of type 'application/
json'
! !      !   NSLog(@"The JSON is %@", [response bodyAsJSON]);
! !      }
! } else if ([response isError]) {
! !      // Response status was either 400..499 or 500..599
! !      NSLog(@"HTTP error, status Code: %@", [response
localizedStatusCodeString]);
! }
}
                                                                        11
Requests with Parameters

- (void)sendRequestWithParams {
! // Simple params
! NSDictionary* paramsDictionary = [NSDictionary
dictionaryWithObjectsAndKeys:
! !      !   !   !   !    !   !  !     @"User", @"name",
! !      !   !   !   !    !   !  !     @"Ciklum", @"company", nil];

! [[RKClient sharedClient] post:@"/contacts" params:paramsDictionary
delegate:self];
!
! // Multi-part params via RKParams!
! RKParams* params = [RKParams paramsWithDictionary:paramsDictionary];
! NSData* imageData = UIImagePNGRepresentation([UIImage
imageNamed:@"picture.jpg"]);
! [params setData:imageData MIMEType:@"image/png" forParam:@"photo"];
! [params setFile:@"bio.txt" forParam:@"attachment"];
! [[RKClient sharedClient] post:@"/contacts" params:params delegate:self];
}




                                                                       12
Reachability
- (void)demoReachability {
! // Check if the network is available
! [[RKClient sharedClient] isNetworkAvailable];
!
! // Register for changes in network availability
! NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
! [center addObserver:self selector:@selector(reachabilityDidChange:)
name:RKReachabilityStateChangedNotification object:nil];
}

- (void)reachabilityDidChange:(NSNotification*)notification {
! RKReachabilityObserver* observer = (RKReachabilityObserver*)
[notification object];
! RKReachabilityNetworkStatus status = [observer networkStatus];
! if (RKReachabilityNotReachable == status) {
! !      NSLog(@"No network access!");
! } else if (RKReachabilityReachableViaWiFi == status) {
! !      NSLog(@"Online via WiFi!");
! } else if (RKReachabilityReachableViaWWAN == status) {
! !      NSLog(@"Online via Edge or 3G!");
! }
}


                                                                         13
Object Mapping 2.0




                     14
Modeling a RESTful Service
         "user": {
            "id":31337,
            "name":"Blake Watters",
            "screen_name":"Blake Watters"
            }




  @interface RKTUser : NSObject

  @property (nonatomic, retain) NSNumber* userID;
  @property (nonatomic, retain) NSString* name;
  @property (nonatomic, retain) NSString* screenName;

  @end


                                                        15
"created_at":"Sat Mar 05 13:39:09 +0000 2011",
"favorited":false,
"id":44029179364253700,
"in_reply_to_screen_name":"JustJenFelice",
"text":"@JustJenFelice Be sure to join the Google Group and
reach out if you need any support!",
"user":{
   "id":208727870,
   "name":"RestKit",
   "screen_name":"RestKit",
   }




                                                         16
Initializing the Object Mapping




                                  17
// Init RestKit
RKObjectManager* objectManager = [RKObjectManager
objectManagerWithBaseURL:@"http://twitter.com"];

// Setup our object mappings
RKObjectMapping* userMapping = [RKObjectMapping mappingForClass:
[RKTUser class]];
[userMapping mapKeyPath:@"id" toAttribute:@"userID"];
[userMapping mapKeyPath:@"screen_name" toAttribute:@"screenName"];
[userMapping mapAttributes:@"name", nil];




                                                                     18
// Setup our object mappings

RKObjectMapping* statusMapping = [RKObjectMapping mappingForClass:
[RKTStatus class]];
[statusMapping mapKeyPathsToAttributes:@"id", @"statusID",
     @"created_at", @"createdAt",
     @"text", @"text",
     @"url", @"urlString",
     @"in_reply_to_screen_name", @"inReplyToScreenName",
     @"favorited", @"isFavorited",
     nil];
[statusMapping mapRelationship:@"user" withObjectMapping:userMapping];

// Update date format so that we can parse Twitter dates properly
// Wed Sep 29 15:31:08 +0000 2010
[statusMapping.dateFormatStrings addObject:@"E MMM d HH:mm:ss Z y"];

// Register our mappings with the provider
[objectManager.mappingProvider setObjectMapping:userMapping
forKeyPath:@"user"];
[objectManager.mappingProvider setObjectMapping:statusMapping
forKeyPath:@"status"];




                                                                         19
Loading Remote Objects

- (void)loadTimeline {
    // Load the object model via RestKit!
    RKObjectManager* objectManager = [RKObjectManager sharedManager];
    RKObjectMapping* statusMapping = nil;

    // Twitter returns statuses as a naked array in JSON, so we instruct
the loader to user the appropriate object mapping
    if ([objectManager.acceptMIMEType isEqualToString:RKMIMETypeJSON]) {
        statusMapping = [objectManager.mappingProvider
objectMappingForKeyPath:@"status"];
    }

    [objectManager loadObjectsAtResourcePath:@"/status/user_timeline/
RestKit" objectMapping:statusMapping delegate:self];
}

- (void)objectLoader:(RKObjectLoader*)objectLoader didLoadObjects:
(NSArray*)objects {
!   NSLog(@"Loaded statuses: %@", objects);
}



                                                                           20
Configuring the Router

- (void)configureRouter {

!   [objectManager.router routeClass:[Contact class] toResourcePath:@"/contacts/
(contactID)"];
!   [objectManager.router routeClass:[Contact class] toResourcePath:@"/contacts"
forMethod:RKRequestMethodPOST];

}




                                                                               21
RESTful Object Manipulation
// Create a new Contact
- (void)createObject {
!   Contact* contact = [Contact new];
!   contact.name = @"RestKit User";
!   contact.email = @"user@restkit.org";
!
!   // POST to /contacts
!   [[RKObjectManager sharedManager] postObject:contact delegate:self];
}

// Edit Contact with ID 12345
- (void)editObject {
!   Contact* contact = [Contact new];
!   contact.contactID = [NSNumber numberWithInt:12345];
!   contact.name = @"New Name";
!
!   // POST to /contacts/12345
!   [[RKObjectManager sharedManager] putObject:contact delegate:self];
}

// Delete Contact with ID 321
- (void)deleteObject {
!   Contact* contact = [Contact new];
!   contact.contactID = [NSNumber numberWithInt:321];
!
!   // DELETE to /contacts/321
!   [[RKObjectManager sharedManager] deleteObject:contact delegate:self];!
}
                                                                             22
Core Data




            23
Configuring CoreData

#import <RestKit/CoreData/CoreData.h>

- (void)configureObjectStore {
  // Initialize the RestKit Object Manager
  RKObjectManager* objectManager = [RKObjectManager
objectManagerWithBaseURL:@"http://restkit.org"];
!
  // Initialize object store
  // We are using the Core Data support, so we have initialized a managed
object store backed
  // with a SQLite database.
  objectManager.objectStore = [RKManagedObjectStore
objectStoreWithStoreFilename:@"Contacts.sqlite"];
}



                                                                            24
Mapping


RKManagedObjectMapping* userMapping = [RKManagedObjectMapping
mappingForEntityWithName:@"RKTUser"];

userMapping.primaryKeyAttribute = @"userID";

[userMapping mapKeyPath:@"id" toAttribute:@"userID"];
[userMapping mapKeyPath:@"screen_name" toAttribute:@"screenName"];
[userMapping mapAttributes:@"name", nil];




                                                                     25
Working with Core Data

//   Adapted from https://github.com/magicalpanda/MagicalRecord


// Get all the Contacts
NSArray* contacts = [Contact allObjects];
!
// Count the Contacts
NSError* error = nil;
NSUInteger count = [Contact count:&error];
!
// Find Contact by primary key
NSNumber* contactID = [NSNumber numberWithInt:12345];
Contact* somebody = [Contact objectWithPrimaryKeyValue:contactID];
!
// Find Contacts with criteria
NSPredicate* predicate = [NSPredicate predicateWithFormat:@"name
contains[cd] 'restkit'"];
NSArray* matches = [Contact objectsWithPredicate:predicate];




                                                                     26
Database Seeding

NSString *seedDatabaseName = nil;
NSString *databaseName = RKDefaultSeedDatabaseFileName;

objectManager.objectStore = [RKManagedObjectStore
objectStoreWithStoreFilename:databaseName
usingSeedDatabaseName:seedDatabaseName managedObjectModel:nil
delegate:self];

RKManagedObjectSeeder* seeder = [RKManagedObjectSeeder
objectSeederWithObjectManager:objectManager];

// Seed DB with instances of RKTStatus from a snapshot of the RestKit
Twitter timeline
[seeder seedObjectsFromFile:@"restkit.json"
withObjectMapping:statusMapping];

// Seed DB with RKTUser objects. The class will be inferred via element
registration
[seeder seedObjectsFromFiles:@"users.json", nil];

// Finalize the seeding and output a helpful informational message
[seeder finalizeSeedingAndExit];


                                                                          27
Pluggable parsing layer
• JSON
- SBJSON
- NXJSON
- YAJL
- JSONKit
• XML



                          28
//   Adapted from https://github.com/magicalpanda/MagicalRecord


// Get all the Contacts
NSArray* contacts = [Contact allObjects];
!
// Count the Contacts
NSError* error = nil;
NSUInteger count = [Contact count:&error];
!
// Find Contact by primary key
NSNumber* contactID = [NSNumber numberWithInt:12345];
Contact* somebody = [Contact objectWithPrimaryKeyValue:contactID];
!
// Find Contacts with criteria
NSPredicate* predicate = [NSPredicate predicateWithFormat:@"name
contains[cd] 'restkit'"];
NSArray* matches = [Contact objectsWithPredicate:predicate];




                                                                     29
Integration Points



Three20
              Ruby on Rails

                              30
http://restkit.org/
         http://twitter.com/restkit
http://github.com/RestKit/RestKit
?

More Related Content

What's hot

Integrate Ruby on Rails with Avectra's NetFORUM xWeb API.
Integrate Ruby on Rails with Avectra's NetFORUM xWeb API.Integrate Ruby on Rails with Avectra's NetFORUM xWeb API.
Integrate Ruby on Rails with Avectra's NetFORUM xWeb API.Thomas Vendetta
 
Simplifying Persistence for Java and MongoDB with Morphia
Simplifying Persistence for Java and MongoDB with MorphiaSimplifying Persistence for Java and MongoDB with Morphia
Simplifying Persistence for Java and MongoDB with MorphiaMongoDB
 
Web Technologies - forms and actions
Web Technologies -  forms and actionsWeb Technologies -  forms and actions
Web Technologies - forms and actionsAren Zomorodian
 
Gwt and rpc use 2007 1
Gwt and rpc use 2007 1Gwt and rpc use 2007 1
Gwt and rpc use 2007 1Sam Muhanguzi
 
Web Services with Objective-C
Web Services with Objective-CWeb Services with Objective-C
Web Services with Objective-CJuio Barros
 
Consume Spring Data Rest with Angularjs
Consume Spring Data Rest with AngularjsConsume Spring Data Rest with Angularjs
Consume Spring Data Rest with AngularjsCorneil du Plessis
 
RMLL 2013 - Synchronize OpenLDAP and Active Directory with LSC
RMLL 2013 - Synchronize OpenLDAP and Active Directory with LSCRMLL 2013 - Synchronize OpenLDAP and Active Directory with LSC
RMLL 2013 - Synchronize OpenLDAP and Active Directory with LSCClément OUDOT
 
Synchronize OpenLDAP with Active Directory with LSC project
Synchronize OpenLDAP with Active Directory with LSC projectSynchronize OpenLDAP with Active Directory with LSC project
Synchronize OpenLDAP with Active Directory with LSC projectClément OUDOT
 
Building multi lingual and empatic bots - Sander van den Hoven - Codemotion A...
Building multi lingual and empatic bots - Sander van den Hoven - Codemotion A...Building multi lingual and empatic bots - Sander van den Hoven - Codemotion A...
Building multi lingual and empatic bots - Sander van den Hoven - Codemotion A...Codemotion
 
Mail OnLine Android Application at DroidCon - Turin - Italy
Mail OnLine Android Application at DroidCon - Turin - ItalyMail OnLine Android Application at DroidCon - Turin - Italy
Mail OnLine Android Application at DroidCon - Turin - ItalyYahoo
 
Intro to IndexedDB (Beta)
Intro to IndexedDB (Beta)Intro to IndexedDB (Beta)
Intro to IndexedDB (Beta)Mike West
 
GR8Conf 2011: Grails Webflow
GR8Conf 2011: Grails WebflowGR8Conf 2011: Grails Webflow
GR8Conf 2011: Grails WebflowGR8Conf
 
Universal JS Web Applications with React - Web Summer Camp 2017, Rovinj (Work...
Universal JS Web Applications with React - Web Summer Camp 2017, Rovinj (Work...Universal JS Web Applications with React - Web Summer Camp 2017, Rovinj (Work...
Universal JS Web Applications with React - Web Summer Camp 2017, Rovinj (Work...Luciano Mammino
 
Cloudbase.io MoSync Reload Course
Cloudbase.io MoSync Reload CourseCloudbase.io MoSync Reload Course
Cloudbase.io MoSync Reload Coursecloudbase.io
 
Grails transactions
Grails   transactionsGrails   transactions
Grails transactionsHusain Dalal
 
Effiziente Datenpersistierung mit JPA 2.1 und Hibernate
Effiziente Datenpersistierung mit JPA 2.1 und HibernateEffiziente Datenpersistierung mit JPA 2.1 und Hibernate
Effiziente Datenpersistierung mit JPA 2.1 und HibernateThorben Janssen
 

What's hot (20)

Integrate Ruby on Rails with Avectra's NetFORUM xWeb API.
Integrate Ruby on Rails with Avectra's NetFORUM xWeb API.Integrate Ruby on Rails with Avectra's NetFORUM xWeb API.
Integrate Ruby on Rails with Avectra's NetFORUM xWeb API.
 
Simplifying Persistence for Java and MongoDB with Morphia
Simplifying Persistence for Java and MongoDB with MorphiaSimplifying Persistence for Java and MongoDB with Morphia
Simplifying Persistence for Java and MongoDB with Morphia
 
Web Technologies - forms and actions
Web Technologies -  forms and actionsWeb Technologies -  forms and actions
Web Technologies - forms and actions
 
Gwt and rpc use 2007 1
Gwt and rpc use 2007 1Gwt and rpc use 2007 1
Gwt and rpc use 2007 1
 
Web Services with Objective-C
Web Services with Objective-CWeb Services with Objective-C
Web Services with Objective-C
 
Consume Spring Data Rest with Angularjs
Consume Spring Data Rest with AngularjsConsume Spring Data Rest with Angularjs
Consume Spring Data Rest with Angularjs
 
JavaScript JQUERY AJAX
JavaScript JQUERY AJAXJavaScript JQUERY AJAX
JavaScript JQUERY AJAX
 
RMLL 2013 - Synchronize OpenLDAP and Active Directory with LSC
RMLL 2013 - Synchronize OpenLDAP and Active Directory with LSCRMLL 2013 - Synchronize OpenLDAP and Active Directory with LSC
RMLL 2013 - Synchronize OpenLDAP and Active Directory with LSC
 
Ajax
AjaxAjax
Ajax
 
Synchronize OpenLDAP with Active Directory with LSC project
Synchronize OpenLDAP with Active Directory with LSC projectSynchronize OpenLDAP with Active Directory with LSC project
Synchronize OpenLDAP with Active Directory with LSC project
 
Building multi lingual and empatic bots - Sander van den Hoven - Codemotion A...
Building multi lingual and empatic bots - Sander van den Hoven - Codemotion A...Building multi lingual and empatic bots - Sander van den Hoven - Codemotion A...
Building multi lingual and empatic bots - Sander van den Hoven - Codemotion A...
 
Mail OnLine Android Application at DroidCon - Turin - Italy
Mail OnLine Android Application at DroidCon - Turin - ItalyMail OnLine Android Application at DroidCon - Turin - Italy
Mail OnLine Android Application at DroidCon - Turin - Italy
 
Xml http request
Xml http requestXml http request
Xml http request
 
Intro to IndexedDB (Beta)
Intro to IndexedDB (Beta)Intro to IndexedDB (Beta)
Intro to IndexedDB (Beta)
 
GR8Conf 2011: Grails Webflow
GR8Conf 2011: Grails WebflowGR8Conf 2011: Grails Webflow
GR8Conf 2011: Grails Webflow
 
Universal JS Web Applications with React - Web Summer Camp 2017, Rovinj (Work...
Universal JS Web Applications with React - Web Summer Camp 2017, Rovinj (Work...Universal JS Web Applications with React - Web Summer Camp 2017, Rovinj (Work...
Universal JS Web Applications with React - Web Summer Camp 2017, Rovinj (Work...
 
Cloudbase.io MoSync Reload Course
Cloudbase.io MoSync Reload CourseCloudbase.io MoSync Reload Course
Cloudbase.io MoSync Reload Course
 
Grails transactions
Grails   transactionsGrails   transactions
Grails transactions
 
Effiziente Datenpersistierung mit JPA 2.1 und Hibernate
Effiziente Datenpersistierung mit JPA 2.1 und HibernateEffiziente Datenpersistierung mit JPA 2.1 und Hibernate
Effiziente Datenpersistierung mit JPA 2.1 und Hibernate
 
Intro to ReactJS
Intro to ReactJSIntro to ReactJS
Intro to ReactJS
 

Similar to MPD2011 | Сергей Клюев "RESTfull iOS with RestKit"

Webエンジニアから見たiOS5
Webエンジニアから見たiOS5Webエンジニアから見たiOS5
Webエンジニアから見たiOS5Satoshi Asano
 
Introduction to Restkit
Introduction to RestkitIntroduction to Restkit
Introduction to Restkitpetertmarks
 
Full stack development with node and NoSQL - All Things Open - October 2017
Full stack development with node and NoSQL - All Things Open - October 2017Full stack development with node and NoSQL - All Things Open - October 2017
Full stack development with node and NoSQL - All Things Open - October 2017Matthew Groves
 
Full Stack Development with Node.js and NoSQL
Full Stack Development with Node.js and NoSQLFull Stack Development with Node.js and NoSQL
Full Stack Development with Node.js and NoSQLAll Things Open
 
Implement Service Broker with Spring Boot #cf_tokyo
Implement Service Broker with Spring Boot #cf_tokyoImplement Service Broker with Spring Boot #cf_tokyo
Implement Service Broker with Spring Boot #cf_tokyoToshiaki Maki
 
CouchDB Mobile - From Couch to 5K in 1 Hour
CouchDB Mobile - From Couch to 5K in 1 HourCouchDB Mobile - From Couch to 5K in 1 Hour
CouchDB Mobile - From Couch to 5K in 1 HourPeter Friese
 
第一次用Parse就深入淺出
第一次用Parse就深入淺出第一次用Parse就深入淺出
第一次用Parse就深入淺出Ymow Wu
 
Spring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. RESTSpring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. RESTSam Brannen
 
Painless Persistence in a Disconnected World
Painless Persistence in a Disconnected WorldPainless Persistence in a Disconnected World
Painless Persistence in a Disconnected WorldChristian Melchior
 
Ember.js - A JavaScript framework for creating ambitious web applications
Ember.js - A JavaScript framework for creating ambitious web applications  Ember.js - A JavaScript framework for creating ambitious web applications
Ember.js - A JavaScript framework for creating ambitious web applications Juliana Lucena
 
Geospatial Graphs made easy with OrientDB - Codemotion Warsaw 2016
Geospatial Graphs made easy with OrientDB - Codemotion Warsaw 2016Geospatial Graphs made easy with OrientDB - Codemotion Warsaw 2016
Geospatial Graphs made easy with OrientDB - Codemotion Warsaw 2016Luigi Dell'Aquila
 
GWT Web Socket and data serialization
GWT Web Socket and data serializationGWT Web Socket and data serialization
GWT Web Socket and data serializationGWTcon
 
Beginning icloud development - Cesare Rocchi - WhyMCA
Beginning icloud development - Cesare Rocchi - WhyMCABeginning icloud development - Cesare Rocchi - WhyMCA
Beginning icloud development - Cesare Rocchi - WhyMCAWhymca
 
«ReactiveCocoa и MVVM» — Николай Касьянов, SoftWear
«ReactiveCocoa и MVVM» — Николай Касьянов, SoftWear«ReactiveCocoa и MVVM» — Николай Касьянов, SoftWear
«ReactiveCocoa и MVVM» — Николай Касьянов, SoftWeare-Legion
 
SproutCore and the Future of Web Apps
SproutCore and the Future of Web AppsSproutCore and the Future of Web Apps
SproutCore and the Future of Web AppsMike Subelsky
 

Similar to MPD2011 | Сергей Клюев "RESTfull iOS with RestKit" (20)

Webエンジニアから見たiOS5
Webエンジニアから見たiOS5Webエンジニアから見たiOS5
Webエンジニアから見たiOS5
 
Introduction to Restkit
Introduction to RestkitIntroduction to Restkit
Introduction to Restkit
 
Full stack development with node and NoSQL - All Things Open - October 2017
Full stack development with node and NoSQL - All Things Open - October 2017Full stack development with node and NoSQL - All Things Open - October 2017
Full stack development with node and NoSQL - All Things Open - October 2017
 
Full Stack Development with Node.js and NoSQL
Full Stack Development with Node.js and NoSQLFull Stack Development with Node.js and NoSQL
Full Stack Development with Node.js and NoSQL
 
Implement Service Broker with Spring Boot #cf_tokyo
Implement Service Broker with Spring Boot #cf_tokyoImplement Service Broker with Spring Boot #cf_tokyo
Implement Service Broker with Spring Boot #cf_tokyo
 
CouchDB Mobile - From Couch to 5K in 1 Hour
CouchDB Mobile - From Couch to 5K in 1 HourCouchDB Mobile - From Couch to 5K in 1 Hour
CouchDB Mobile - From Couch to 5K in 1 Hour
 
第一次用Parse就深入淺出
第一次用Parse就深入淺出第一次用Parse就深入淺出
第一次用Parse就深入淺出
 
UIWebView Tips
UIWebView TipsUIWebView Tips
UIWebView Tips
 
Exploring Relay land
Exploring Relay landExploring Relay land
Exploring Relay land
 
Intro to Sail.js
Intro to Sail.jsIntro to Sail.js
Intro to Sail.js
 
Spring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. RESTSpring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. REST
 
Painless Persistence in a Disconnected World
Painless Persistence in a Disconnected WorldPainless Persistence in a Disconnected World
Painless Persistence in a Disconnected World
 
Requery overview
Requery overviewRequery overview
Requery overview
 
iOS for ERREST
iOS for ERRESTiOS for ERREST
iOS for ERREST
 
Ember.js - A JavaScript framework for creating ambitious web applications
Ember.js - A JavaScript framework for creating ambitious web applications  Ember.js - A JavaScript framework for creating ambitious web applications
Ember.js - A JavaScript framework for creating ambitious web applications
 
Geospatial Graphs made easy with OrientDB - Codemotion Warsaw 2016
Geospatial Graphs made easy with OrientDB - Codemotion Warsaw 2016Geospatial Graphs made easy with OrientDB - Codemotion Warsaw 2016
Geospatial Graphs made easy with OrientDB - Codemotion Warsaw 2016
 
GWT Web Socket and data serialization
GWT Web Socket and data serializationGWT Web Socket and data serialization
GWT Web Socket and data serialization
 
Beginning icloud development - Cesare Rocchi - WhyMCA
Beginning icloud development - Cesare Rocchi - WhyMCABeginning icloud development - Cesare Rocchi - WhyMCA
Beginning icloud development - Cesare Rocchi - WhyMCA
 
«ReactiveCocoa и MVVM» — Николай Касьянов, SoftWear
«ReactiveCocoa и MVVM» — Николай Касьянов, SoftWear«ReactiveCocoa и MVVM» — Николай Касьянов, SoftWear
«ReactiveCocoa и MVVM» — Николай Касьянов, SoftWear
 
SproutCore and the Future of Web Apps
SproutCore and the Future of Web AppsSproutCore and the Future of Web Apps
SproutCore and the Future of Web Apps
 

More from ITGinGer

MPD2011 | Дмитрий Дворниченко "Гайдлайны — не предел"
MPD2011 | Дмитрий Дворниченко "Гайдлайны — не предел"MPD2011 | Дмитрий Дворниченко "Гайдлайны — не предел"
MPD2011 | Дмитрий Дворниченко "Гайдлайны — не предел"ITGinGer
 
MPD2011 | Андрей Михайлов "Как ускорить и удешевить разработку мобильного при...
MPD2011 | Андрей Михайлов "Как ускорить и удешевить разработку мобильного при...MPD2011 | Андрей Михайлов "Как ускорить и удешевить разработку мобильного при...
MPD2011 | Андрей Михайлов "Как ускорить и удешевить разработку мобильного при...ITGinGer
 
MPD2011 | Галина Рыженко "Дополненная реальность (Augmented reality)"
MPD2011 | Галина Рыженко "Дополненная реальность (Augmented reality)"MPD2011 | Галина Рыженко "Дополненная реальность (Augmented reality)"
MPD2011 | Галина Рыженко "Дополненная реальность (Augmented reality)"ITGinGer
 
MPD2011 | Олег Донцов "Введение в разработку bada Flash & Web приложений"
MPD2011 | Олег Донцов "Введение в разработку bada Flash & Web приложений"MPD2011 | Олег Донцов "Введение в разработку bada Flash & Web приложений"
MPD2011 | Олег Донцов "Введение в разработку bada Flash & Web приложений"ITGinGer
 
MPD2011 | Андрей Митрошин "Новые возможности в bada2.0 Обзор функциональности...
MPD2011 | Андрей Митрошин "Новые возможности в bada2.0 Обзор функциональности...MPD2011 | Андрей Митрошин "Новые возможности в bada2.0 Обзор функциональности...
MPD2011 | Андрей Митрошин "Новые возможности в bada2.0 Обзор функциональности...ITGinGer
 
MPD2011 | Тарас Филатов "Эволюция мобильных приложений. Через Cloud и Social ...
MPD2011 | Тарас Филатов "Эволюция мобильных приложений. Через Cloud и Social ...MPD2011 | Тарас Филатов "Эволюция мобильных приложений. Через Cloud и Social ...
MPD2011 | Тарас Филатов "Эволюция мобильных приложений. Через Cloud и Social ...ITGinGer
 
MPD2011 | Леонид Юрченко "Продажи внутри мобильных приложений"
MPD2011 | Леонид Юрченко "Продажи внутри мобильных приложений"MPD2011 | Леонид Юрченко "Продажи внутри мобильных приложений"
MPD2011 | Леонид Юрченко "Продажи внутри мобильных приложений"ITGinGer
 
MPD2011 | Роман Харченко "Самое самое в XCode 4.2 и iOS 5.0 с точки зрения ра...
MPD2011 | Роман Харченко "Самое самое в XCode 4.2 и iOS 5.0 с точки зрения ра...MPD2011 | Роман Харченко "Самое самое в XCode 4.2 и iOS 5.0 с точки зрения ра...
MPD2011 | Роман Харченко "Самое самое в XCode 4.2 и iOS 5.0 с точки зрения ра...ITGinGer
 
MPD2011 | Тимур Гарифзянов "Субъективный взгляд на WP7"
MPD2011 | Тимур Гарифзянов "Субъективный взгляд на WP7"MPD2011 | Тимур Гарифзянов "Субъективный взгляд на WP7"
MPD2011 | Тимур Гарифзянов "Субъективный взгляд на WP7"ITGinGer
 
MPD2011 | Павел Кравченко "Гибкие методологии в мобильной разработке"
MPD2011 | Павел Кравченко "Гибкие методологии в мобильной разработке"MPD2011 | Павел Кравченко "Гибкие методологии в мобильной разработке"
MPD2011 | Павел Кравченко "Гибкие методологии в мобильной разработке"ITGinGer
 
MPD2011 | Роман Мазур "С чего начать Android разработчику"
MPD2011 | Роман Мазур "С чего начать Android разработчику"MPD2011 | Роман Мазур "С чего начать Android разработчику"
MPD2011 | Роман Мазур "С чего начать Android разработчику"ITGinGer
 
MPD2011 | Александр Додатко "Процесс непрерывной интеграции для iOS проектов"
MPD2011 | Александр Додатко "Процесс непрерывной интеграции для iOS проектов"MPD2011 | Александр Додатко "Процесс непрерывной интеграции для iOS проектов"
MPD2011 | Александр Додатко "Процесс непрерывной интеграции для iOS проектов"ITGinGer
 
MPD2011 | Александр Егошин "Мобильные игры: разработка – это только полдела"
MPD2011 | Александр Егошин "Мобильные игры: разработка – это только полдела"MPD2011 | Александр Егошин "Мобильные игры: разработка – это только полдела"
MPD2011 | Александр Егошин "Мобильные игры: разработка – это только полдела"ITGinGer
 
Андрей Чипиленко - "Разработка мобильного приложения для интернет‐мага...
Андрей Чипиленко - "Разработка мобильного	   приложения	    для интернет‐мага...Андрей Чипиленко - "Разработка мобильного	   приложения	    для интернет‐мага...
Андрей Чипиленко - "Разработка мобильного приложения для интернет‐мага...ITGinGer
 
Стас Городниченко - "Почему мобильная коммерция сейчас интересна для инвестор...
Стас Городниченко - "Почему мобильная коммерция сейчас интересна для инвестор...Стас Городниченко - "Почему мобильная коммерция сейчас интересна для инвестор...
Стас Городниченко - "Почему мобильная коммерция сейчас интересна для инвестор...ITGinGer
 
Андрей Чипиленко - "2D фреймворки для iOS" at Tech Talk, Global Logic
Андрей Чипиленко - "2D фреймворки для iOS" at Tech Talk, Global LogicАндрей Чипиленко - "2D фреймворки для iOS" at Tech Talk, Global Logic
Андрей Чипиленко - "2D фреймворки для iOS" at Tech Talk, Global LogicITGinGer
 
Стас Городниченко - "Мобильная коммерция: вчера, сегодня, завтра" at Tech Tal...
Стас Городниченко - "Мобильная коммерция: вчера, сегодня, завтра" at Tech Tal...Стас Городниченко - "Мобильная коммерция: вчера, сегодня, завтра" at Tech Tal...
Стас Городниченко - "Мобильная коммерция: вчера, сегодня, завтра" at Tech Tal...ITGinGer
 

More from ITGinGer (17)

MPD2011 | Дмитрий Дворниченко "Гайдлайны — не предел"
MPD2011 | Дмитрий Дворниченко "Гайдлайны — не предел"MPD2011 | Дмитрий Дворниченко "Гайдлайны — не предел"
MPD2011 | Дмитрий Дворниченко "Гайдлайны — не предел"
 
MPD2011 | Андрей Михайлов "Как ускорить и удешевить разработку мобильного при...
MPD2011 | Андрей Михайлов "Как ускорить и удешевить разработку мобильного при...MPD2011 | Андрей Михайлов "Как ускорить и удешевить разработку мобильного при...
MPD2011 | Андрей Михайлов "Как ускорить и удешевить разработку мобильного при...
 
MPD2011 | Галина Рыженко "Дополненная реальность (Augmented reality)"
MPD2011 | Галина Рыженко "Дополненная реальность (Augmented reality)"MPD2011 | Галина Рыженко "Дополненная реальность (Augmented reality)"
MPD2011 | Галина Рыженко "Дополненная реальность (Augmented reality)"
 
MPD2011 | Олег Донцов "Введение в разработку bada Flash & Web приложений"
MPD2011 | Олег Донцов "Введение в разработку bada Flash & Web приложений"MPD2011 | Олег Донцов "Введение в разработку bada Flash & Web приложений"
MPD2011 | Олег Донцов "Введение в разработку bada Flash & Web приложений"
 
MPD2011 | Андрей Митрошин "Новые возможности в bada2.0 Обзор функциональности...
MPD2011 | Андрей Митрошин "Новые возможности в bada2.0 Обзор функциональности...MPD2011 | Андрей Митрошин "Новые возможности в bada2.0 Обзор функциональности...
MPD2011 | Андрей Митрошин "Новые возможности в bada2.0 Обзор функциональности...
 
MPD2011 | Тарас Филатов "Эволюция мобильных приложений. Через Cloud и Social ...
MPD2011 | Тарас Филатов "Эволюция мобильных приложений. Через Cloud и Social ...MPD2011 | Тарас Филатов "Эволюция мобильных приложений. Через Cloud и Social ...
MPD2011 | Тарас Филатов "Эволюция мобильных приложений. Через Cloud и Social ...
 
MPD2011 | Леонид Юрченко "Продажи внутри мобильных приложений"
MPD2011 | Леонид Юрченко "Продажи внутри мобильных приложений"MPD2011 | Леонид Юрченко "Продажи внутри мобильных приложений"
MPD2011 | Леонид Юрченко "Продажи внутри мобильных приложений"
 
MPD2011 | Роман Харченко "Самое самое в XCode 4.2 и iOS 5.0 с точки зрения ра...
MPD2011 | Роман Харченко "Самое самое в XCode 4.2 и iOS 5.0 с точки зрения ра...MPD2011 | Роман Харченко "Самое самое в XCode 4.2 и iOS 5.0 с точки зрения ра...
MPD2011 | Роман Харченко "Самое самое в XCode 4.2 и iOS 5.0 с точки зрения ра...
 
MPD2011 | Тимур Гарифзянов "Субъективный взгляд на WP7"
MPD2011 | Тимур Гарифзянов "Субъективный взгляд на WP7"MPD2011 | Тимур Гарифзянов "Субъективный взгляд на WP7"
MPD2011 | Тимур Гарифзянов "Субъективный взгляд на WP7"
 
MPD2011 | Павел Кравченко "Гибкие методологии в мобильной разработке"
MPD2011 | Павел Кравченко "Гибкие методологии в мобильной разработке"MPD2011 | Павел Кравченко "Гибкие методологии в мобильной разработке"
MPD2011 | Павел Кравченко "Гибкие методологии в мобильной разработке"
 
MPD2011 | Роман Мазур "С чего начать Android разработчику"
MPD2011 | Роман Мазур "С чего начать Android разработчику"MPD2011 | Роман Мазур "С чего начать Android разработчику"
MPD2011 | Роман Мазур "С чего начать Android разработчику"
 
MPD2011 | Александр Додатко "Процесс непрерывной интеграции для iOS проектов"
MPD2011 | Александр Додатко "Процесс непрерывной интеграции для iOS проектов"MPD2011 | Александр Додатко "Процесс непрерывной интеграции для iOS проектов"
MPD2011 | Александр Додатко "Процесс непрерывной интеграции для iOS проектов"
 
MPD2011 | Александр Егошин "Мобильные игры: разработка – это только полдела"
MPD2011 | Александр Егошин "Мобильные игры: разработка – это только полдела"MPD2011 | Александр Егошин "Мобильные игры: разработка – это только полдела"
MPD2011 | Александр Егошин "Мобильные игры: разработка – это только полдела"
 
Андрей Чипиленко - "Разработка мобильного приложения для интернет‐мага...
Андрей Чипиленко - "Разработка мобильного	   приложения	    для интернет‐мага...Андрей Чипиленко - "Разработка мобильного	   приложения	    для интернет‐мага...
Андрей Чипиленко - "Разработка мобильного приложения для интернет‐мага...
 
Стас Городниченко - "Почему мобильная коммерция сейчас интересна для инвестор...
Стас Городниченко - "Почему мобильная коммерция сейчас интересна для инвестор...Стас Городниченко - "Почему мобильная коммерция сейчас интересна для инвестор...
Стас Городниченко - "Почему мобильная коммерция сейчас интересна для инвестор...
 
Андрей Чипиленко - "2D фреймворки для iOS" at Tech Talk, Global Logic
Андрей Чипиленко - "2D фреймворки для iOS" at Tech Talk, Global LogicАндрей Чипиленко - "2D фреймворки для iOS" at Tech Talk, Global Logic
Андрей Чипиленко - "2D фреймворки для iOS" at Tech Talk, Global Logic
 
Стас Городниченко - "Мобильная коммерция: вчера, сегодня, завтра" at Tech Tal...
Стас Городниченко - "Мобильная коммерция: вчера, сегодня, завтра" at Tech Tal...Стас Городниченко - "Мобильная коммерция: вчера, сегодня, завтра" at Tech Tal...
Стас Городниченко - "Мобильная коммерция: вчера, сегодня, завтра" at Tech Tal...
 

Recently uploaded

MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelDeepika Singh
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024The Digital Insurer
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfOverkill Security
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Zilliz
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 

Recently uploaded (20)

MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 

MPD2011 | Сергей Клюев "RESTfull iOS with RestKit"

  • 1. RESTful iOS with RestKit Taras Kalapun Sergey Kluev
  • 3. 3
  • 4. 4
  • 5. RestKit Architecture • Network Layer • Object Mapping • Core Data • Pluggable parsing layer • Integration Points 5
  • 7. Key Concepts • RKClient - Your user agent • Base URLs and Resource Paths • RKRequest & RKResponse - The HTTP lifecycle • RKRequestQueue - A lightweight queue implementation • RKParams - Multi-part MIME requests • Reachability - Detecting offline/online status 7
  • 8. RKClient • Sending Asynchronous Requests 1 – get:delegate: 2 – get:queryParams:delegate: 3 – post:params:delegate: 4 – put:params:delegate: 5 – delete:delegate: 8
  • 9. Initializing RKClient - (void)initRKClient { ! // Initialize with a Base URL ! RKClient* client = [RKClient clientWithBaseURL:@"http://restkit.org"]; ! ! // Setup HTTP AUTH ! client.username = @"restkit"; ! client.password = @"rocks"; ! ! // Set an app-wide API key HTTP header ! [client setValue:@"123456" forHTTPHeaderField:@"X-RESTKIT-API-KEY"]; ! ! // The first initialized RKClient becomes ! // the sharedClient instance ! [[RKClient sharedClient] isNetworkAvailable]; } 9
  • 10. Sending Requests - (void)sendRequest { ! // Send an HTTP GET request to 'http://restkit.org/contacts' ! [[RKClient sharedClient] get:@"/contacts" delegate:self]; } // RKRequestDelegate methods - (void)request:(RKRequest*)request didLoadResponse:(RKResponse*)response { ! NSLog(@"Yay! We Got a response"); } - (void)request:(RKRequest*)request didFailLoadWithError:(NSError*)error { ! NSLog(@"Oh no! Error: %@", [error localizedDescription]); } 10
  • 11. Processing Responses - (void)sendRequest { ! // Send an HTTP GET request to 'http://restkit.org/contacts' ! [[RKClient sharedClient] get:@"/contacts" delegate:self]; } - (void)request:(RKRequest*)request didLoadResponse:(RKResponse*)response { ! NSLog(@"Request Headers: %@", [response allHeaderFields]); ! NSLog(@"Cookies: %@", [response cookies]) ! ! if ([response isSuccessful]) { ! ! // Response status was 200..299 ! ! if ([response isCreated] && [response isJSON]) { ! ! ! // Looks like we have a 201 response of type 'application/ json' ! ! ! NSLog(@"The JSON is %@", [response bodyAsJSON]); ! ! } ! } else if ([response isError]) { ! ! // Response status was either 400..499 or 500..599 ! ! NSLog(@"HTTP error, status Code: %@", [response localizedStatusCodeString]); ! } } 11
  • 12. Requests with Parameters - (void)sendRequestWithParams { ! // Simple params ! NSDictionary* paramsDictionary = [NSDictionary dictionaryWithObjectsAndKeys: ! ! ! ! ! ! ! ! ! @"User", @"name", ! ! ! ! ! ! ! ! ! @"Ciklum", @"company", nil]; ! [[RKClient sharedClient] post:@"/contacts" params:paramsDictionary delegate:self]; ! ! // Multi-part params via RKParams! ! RKParams* params = [RKParams paramsWithDictionary:paramsDictionary]; ! NSData* imageData = UIImagePNGRepresentation([UIImage imageNamed:@"picture.jpg"]); ! [params setData:imageData MIMEType:@"image/png" forParam:@"photo"]; ! [params setFile:@"bio.txt" forParam:@"attachment"]; ! [[RKClient sharedClient] post:@"/contacts" params:params delegate:self]; } 12
  • 13. Reachability - (void)demoReachability { ! // Check if the network is available ! [[RKClient sharedClient] isNetworkAvailable]; ! ! // Register for changes in network availability ! NSNotificationCenter* center = [NSNotificationCenter defaultCenter]; ! [center addObserver:self selector:@selector(reachabilityDidChange:) name:RKReachabilityStateChangedNotification object:nil]; } - (void)reachabilityDidChange:(NSNotification*)notification { ! RKReachabilityObserver* observer = (RKReachabilityObserver*) [notification object]; ! RKReachabilityNetworkStatus status = [observer networkStatus]; ! if (RKReachabilityNotReachable == status) { ! ! NSLog(@"No network access!"); ! } else if (RKReachabilityReachableViaWiFi == status) { ! ! NSLog(@"Online via WiFi!"); ! } else if (RKReachabilityReachableViaWWAN == status) { ! ! NSLog(@"Online via Edge or 3G!"); ! } } 13
  • 15. Modeling a RESTful Service "user": { "id":31337, "name":"Blake Watters", "screen_name":"Blake Watters" } @interface RKTUser : NSObject @property (nonatomic, retain) NSNumber* userID; @property (nonatomic, retain) NSString* name; @property (nonatomic, retain) NSString* screenName; @end 15
  • 16. "created_at":"Sat Mar 05 13:39:09 +0000 2011", "favorited":false, "id":44029179364253700, "in_reply_to_screen_name":"JustJenFelice", "text":"@JustJenFelice Be sure to join the Google Group and reach out if you need any support!", "user":{ "id":208727870, "name":"RestKit", "screen_name":"RestKit", } 16
  • 18. // Init RestKit RKObjectManager* objectManager = [RKObjectManager objectManagerWithBaseURL:@"http://twitter.com"]; // Setup our object mappings RKObjectMapping* userMapping = [RKObjectMapping mappingForClass: [RKTUser class]]; [userMapping mapKeyPath:@"id" toAttribute:@"userID"]; [userMapping mapKeyPath:@"screen_name" toAttribute:@"screenName"]; [userMapping mapAttributes:@"name", nil]; 18
  • 19. // Setup our object mappings RKObjectMapping* statusMapping = [RKObjectMapping mappingForClass: [RKTStatus class]]; [statusMapping mapKeyPathsToAttributes:@"id", @"statusID", @"created_at", @"createdAt", @"text", @"text", @"url", @"urlString", @"in_reply_to_screen_name", @"inReplyToScreenName", @"favorited", @"isFavorited", nil]; [statusMapping mapRelationship:@"user" withObjectMapping:userMapping]; // Update date format so that we can parse Twitter dates properly // Wed Sep 29 15:31:08 +0000 2010 [statusMapping.dateFormatStrings addObject:@"E MMM d HH:mm:ss Z y"]; // Register our mappings with the provider [objectManager.mappingProvider setObjectMapping:userMapping forKeyPath:@"user"]; [objectManager.mappingProvider setObjectMapping:statusMapping forKeyPath:@"status"]; 19
  • 20. Loading Remote Objects - (void)loadTimeline { // Load the object model via RestKit! RKObjectManager* objectManager = [RKObjectManager sharedManager]; RKObjectMapping* statusMapping = nil; // Twitter returns statuses as a naked array in JSON, so we instruct the loader to user the appropriate object mapping if ([objectManager.acceptMIMEType isEqualToString:RKMIMETypeJSON]) { statusMapping = [objectManager.mappingProvider objectMappingForKeyPath:@"status"]; } [objectManager loadObjectsAtResourcePath:@"/status/user_timeline/ RestKit" objectMapping:statusMapping delegate:self]; } - (void)objectLoader:(RKObjectLoader*)objectLoader didLoadObjects: (NSArray*)objects { ! NSLog(@"Loaded statuses: %@", objects); } 20
  • 21. Configuring the Router - (void)configureRouter { ! [objectManager.router routeClass:[Contact class] toResourcePath:@"/contacts/ (contactID)"]; ! [objectManager.router routeClass:[Contact class] toResourcePath:@"/contacts" forMethod:RKRequestMethodPOST]; } 21
  • 22. RESTful Object Manipulation // Create a new Contact - (void)createObject { ! Contact* contact = [Contact new]; ! contact.name = @"RestKit User"; ! contact.email = @"user@restkit.org"; ! ! // POST to /contacts ! [[RKObjectManager sharedManager] postObject:contact delegate:self]; } // Edit Contact with ID 12345 - (void)editObject { ! Contact* contact = [Contact new]; ! contact.contactID = [NSNumber numberWithInt:12345]; ! contact.name = @"New Name"; ! ! // POST to /contacts/12345 ! [[RKObjectManager sharedManager] putObject:contact delegate:self]; } // Delete Contact with ID 321 - (void)deleteObject { ! Contact* contact = [Contact new]; ! contact.contactID = [NSNumber numberWithInt:321]; ! ! // DELETE to /contacts/321 ! [[RKObjectManager sharedManager] deleteObject:contact delegate:self];! } 22
  • 23. Core Data 23
  • 24. Configuring CoreData #import <RestKit/CoreData/CoreData.h> - (void)configureObjectStore { // Initialize the RestKit Object Manager RKObjectManager* objectManager = [RKObjectManager objectManagerWithBaseURL:@"http://restkit.org"]; ! // Initialize object store // We are using the Core Data support, so we have initialized a managed object store backed // with a SQLite database. objectManager.objectStore = [RKManagedObjectStore objectStoreWithStoreFilename:@"Contacts.sqlite"]; } 24
  • 25. Mapping RKManagedObjectMapping* userMapping = [RKManagedObjectMapping mappingForEntityWithName:@"RKTUser"]; userMapping.primaryKeyAttribute = @"userID"; [userMapping mapKeyPath:@"id" toAttribute:@"userID"]; [userMapping mapKeyPath:@"screen_name" toAttribute:@"screenName"]; [userMapping mapAttributes:@"name", nil]; 25
  • 26. Working with Core Data // Adapted from https://github.com/magicalpanda/MagicalRecord // Get all the Contacts NSArray* contacts = [Contact allObjects]; ! // Count the Contacts NSError* error = nil; NSUInteger count = [Contact count:&error]; ! // Find Contact by primary key NSNumber* contactID = [NSNumber numberWithInt:12345]; Contact* somebody = [Contact objectWithPrimaryKeyValue:contactID]; ! // Find Contacts with criteria NSPredicate* predicate = [NSPredicate predicateWithFormat:@"name contains[cd] 'restkit'"]; NSArray* matches = [Contact objectsWithPredicate:predicate]; 26
  • 27. Database Seeding NSString *seedDatabaseName = nil; NSString *databaseName = RKDefaultSeedDatabaseFileName; objectManager.objectStore = [RKManagedObjectStore objectStoreWithStoreFilename:databaseName usingSeedDatabaseName:seedDatabaseName managedObjectModel:nil delegate:self]; RKManagedObjectSeeder* seeder = [RKManagedObjectSeeder objectSeederWithObjectManager:objectManager]; // Seed DB with instances of RKTStatus from a snapshot of the RestKit Twitter timeline [seeder seedObjectsFromFile:@"restkit.json" withObjectMapping:statusMapping]; // Seed DB with RKTUser objects. The class will be inferred via element registration [seeder seedObjectsFromFiles:@"users.json", nil]; // Finalize the seeding and output a helpful informational message [seeder finalizeSeedingAndExit]; 27
  • 28. Pluggable parsing layer • JSON - SBJSON - NXJSON - YAJL - JSONKit • XML 28
  • 29. // Adapted from https://github.com/magicalpanda/MagicalRecord // Get all the Contacts NSArray* contacts = [Contact allObjects]; ! // Count the Contacts NSError* error = nil; NSUInteger count = [Contact count:&error]; ! // Find Contact by primary key NSNumber* contactID = [NSNumber numberWithInt:12345]; Contact* somebody = [Contact objectWithPrimaryKeyValue:contactID]; ! // Find Contacts with criteria NSPredicate* predicate = [NSPredicate predicateWithFormat:@"name contains[cd] 'restkit'"]; NSArray* matches = [Contact objectsWithPredicate:predicate]; 29
  • 30. Integration Points Three20 Ruby on Rails 30
  • 31. http://restkit.org/ http://twitter.com/restkit http://github.com/RestKit/RestKit
  • 32. ?