SlideShare une entreprise Scribd logo
1  sur  29
RESTfull iOS with RestKit
            Taras Kalapun
What is RestKit?




                   2
3
RestKit is a RESTful Object Mapping Framework
                    for Cocoa

- (void)loadData {
   RKObjectManager* objectManager = [RKObjectManager sharedManager];
   RKObjectMapping* 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);
}

- (void)objectLoader:(RKObjectLoader*)objectLoader didFailWithError:(NSError*)error {

    NSLog(@"Hit error: %@", error);
}


                                                                                        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
• RKParams - Multi-part MIME requests
• Reachability - Detecting of ine/online status



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




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




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

   }
}


                                                                                           10
Requests with Parameters

- (void)sendRequestWithParams {

   // Simple params

   NSDictionary* paramsDictionary = [NSDictionary dictionaryWithObjectsAndKeys:

   
      
   
    
    
    
    
    
      @"Taras Kalapun", @"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];
}




                                                                                        11
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!");

   }
}

                                                                                          12
Object Mapping 2.0




                     13
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


                                                        14
"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",
   }




                                                         15
Initializing the Object Mapping




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




                                                                           17
// 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"];




                                                                                       18
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);
}



                                                                                           19
Con guring the Router

- (void)configureRouter {


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

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

}




                                                                                                 20
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];
}                                                                             21
Core Data




            22
Con guring 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"];
}



                                                                                         23
Mapping


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

userMapping.primaryKeyAttribute = @"userID";

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




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




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




                                                                                         26
Integration Points


Three20
              Ruby on Rails

                              27
http://restkit.org/
        http://twitter.com/restkit
http://github.com/RestKit/RestKit
?
Taras Kalapun
iOS dev, Team lead, it-specialist


t.kalapun@gmail.com
Skype: t.kalapun

Contenu connexe

Tendances

Xa transactions over camel routes
Xa transactions over camel routesXa transactions over camel routes
Xa transactions over camel routesJosué Neis
 
ZendCon2010 Doctrine MongoDB ODM
ZendCon2010 Doctrine MongoDB ODMZendCon2010 Doctrine MongoDB ODM
ZendCon2010 Doctrine MongoDB ODMJonathan Wage
 
Integration of Backbone.js with Spring 3.1
Integration of Backbone.js with Spring 3.1Integration of Backbone.js with Spring 3.1
Integration of Backbone.js with Spring 3.1Michał Orman
 
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
 
Entity Framework Core & Micro-Orms with Asp.Net Core
Entity Framework Core & Micro-Orms with Asp.Net CoreEntity Framework Core & Micro-Orms with Asp.Net Core
Entity Framework Core & Micro-Orms with Asp.Net CoreStephane Belkheraz
 
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
 
Repetition is bad, repetition is bad.
Repetition is bad, repetition is bad.Repetition is bad, repetition is bad.
Repetition is bad, repetition is bad.Michele Giacobazzi
 
OSGi and Spring Data for simple (Web) Application Development - Christian Bar...
OSGi and Spring Data for simple (Web) Application Development - Christian Bar...OSGi and Spring Data for simple (Web) Application Development - Christian Bar...
OSGi and Spring Data for simple (Web) Application Development - Christian Bar...mfrancis
 
GR8Conf 2011: Grails Webflow
GR8Conf 2011: Grails WebflowGR8Conf 2011: Grails Webflow
GR8Conf 2011: Grails WebflowGR8Conf
 
Simplify AJAX using jQuery
Simplify AJAX using jQuerySimplify AJAX using jQuery
Simplify AJAX using jQuerySiva Arunachalam
 
Grails transactions
Grails   transactionsGrails   transactions
Grails transactionsHusain Dalal
 

Tendances (17)

Ajax chap 2.-part 1
Ajax chap 2.-part 1Ajax chap 2.-part 1
Ajax chap 2.-part 1
 
Ajax chap 3
Ajax chap 3Ajax chap 3
Ajax chap 3
 
Xa transactions over camel routes
Xa transactions over camel routesXa transactions over camel routes
Xa transactions over camel routes
 
ZendCon2010 Doctrine MongoDB ODM
ZendCon2010 Doctrine MongoDB ODMZendCon2010 Doctrine MongoDB ODM
ZendCon2010 Doctrine MongoDB ODM
 
Integration of Backbone.js with Spring 3.1
Integration of Backbone.js with Spring 3.1Integration of Backbone.js with Spring 3.1
Integration of Backbone.js with Spring 3.1
 
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...
 
Entity Framework Core & Micro-Orms with Asp.Net Core
Entity Framework Core & Micro-Orms with Asp.Net CoreEntity Framework Core & Micro-Orms with Asp.Net Core
Entity Framework Core & Micro-Orms with Asp.Net Core
 
Consume Spring Data Rest with Angularjs
Consume Spring Data Rest with AngularjsConsume Spring Data Rest with Angularjs
Consume Spring Data Rest with Angularjs
 
Repetition is bad, repetition is bad.
Repetition is bad, repetition is bad.Repetition is bad, repetition is bad.
Repetition is bad, repetition is bad.
 
OSGi and Spring Data for simple (Web) Application Development - Christian Bar...
OSGi and Spring Data for simple (Web) Application Development - Christian Bar...OSGi and Spring Data for simple (Web) Application Development - Christian Bar...
OSGi and Spring Data for simple (Web) Application Development - Christian Bar...
 
JavaCro'15 - GWT integration with Vaadin - Peter Lehto
JavaCro'15 - GWT integration with Vaadin - Peter LehtoJavaCro'15 - GWT integration with Vaadin - Peter Lehto
JavaCro'15 - GWT integration with Vaadin - Peter Lehto
 
SQLite with UWP
SQLite with UWPSQLite with UWP
SQLite with UWP
 
GR8Conf 2011: Grails Webflow
GR8Conf 2011: Grails WebflowGR8Conf 2011: Grails Webflow
GR8Conf 2011: Grails Webflow
 
SOLID Principles
SOLID PrinciplesSOLID Principles
SOLID Principles
 
Django at the Disco
Django at the DiscoDjango at the Disco
Django at the Disco
 
Simplify AJAX using jQuery
Simplify AJAX using jQuerySimplify AJAX using jQuery
Simplify AJAX using jQuery
 
Grails transactions
Grails   transactionsGrails   transactions
Grails transactions
 

Similaire à RESTfull with RestKit

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.Oleg Shanyuk
 
Introduction to Restkit
Introduction to RestkitIntroduction to Restkit
Introduction to Restkitpetertmarks
 
Webエンジニアから見たiOS5
Webエンジニアから見たiOS5Webエンジニアから見たiOS5
Webエンジニアから見たiOS5Satoshi Asano
 
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
 
Beginning icloud development - Cesare Rocchi - WhyMCA
Beginning icloud development - Cesare Rocchi - WhyMCABeginning icloud development - Cesare Rocchi - WhyMCA
Beginning icloud development - Cesare Rocchi - WhyMCAWhymca
 
Gdg dev fest hybrid apps your own mini-cordova
Gdg dev fest hybrid apps  your own mini-cordovaGdg dev fest hybrid apps  your own mini-cordova
Gdg dev fest hybrid apps your own mini-cordovaAyman Mahfouz
 
Spring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. RESTSpring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. RESTSam Brannen
 
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
 
Flask and Angular: An approach to build robust platforms
Flask and Angular:  An approach to build robust platformsFlask and Angular:  An approach to build robust platforms
Flask and Angular: An approach to build robust platformsAyush Sharma
 
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
 
GraphQL, Redux, and React
GraphQL, Redux, and ReactGraphQL, Redux, and React
GraphQL, Redux, and ReactKeon Kim
 
JAX-RS 2.0: New and Noteworthy in RESTful Web Services API - Arun Gupta
JAX-RS 2.0: New and Noteworthy in RESTful Web Services API - Arun GuptaJAX-RS 2.0: New and Noteworthy in RESTful Web Services API - Arun Gupta
JAX-RS 2.0: New and Noteworthy in RESTful Web Services API - Arun GuptaJAX London
 
Developing web-apps like it's 2013
Developing web-apps like it's 2013Developing web-apps like it's 2013
Developing web-apps like it's 2013Laurent_VB
 

Similaire à RESTfull with RestKit (20)

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.
 
Introduction to Restkit
Introduction to RestkitIntroduction to Restkit
Introduction to Restkit
 
Webエンジニアから見たiOS5
Webエンジニアから見たiOS5Webエンジニアから見たiOS5
Webエンジニアから見たiOS5
 
UIWebView Tips
UIWebView TipsUIWebView Tips
UIWebView Tips
 
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
 
Beginning icloud development - Cesare Rocchi - WhyMCA
Beginning icloud development - Cesare Rocchi - WhyMCABeginning icloud development - Cesare Rocchi - WhyMCA
Beginning icloud development - Cesare Rocchi - WhyMCA
 
Gdg dev fest hybrid apps your own mini-cordova
Gdg dev fest hybrid apps  your own mini-cordovaGdg dev fest hybrid apps  your own mini-cordova
Gdg dev fest hybrid apps your own mini-cordova
 
Spring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. RESTSpring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. REST
 
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
 
I os 13
I os 13I os 13
I os 13
 
Flask and Angular: An approach to build robust platforms
Flask and Angular:  An approach to build robust platformsFlask and Angular:  An approach to build robust platforms
Flask and Angular: An approach to build robust platforms
 
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
 
GraphQL, Redux, and React
GraphQL, Redux, and ReactGraphQL, Redux, and React
GraphQL, Redux, and React
 
Requery overview
Requery overviewRequery overview
Requery overview
 
JAX-RS 2.0: New and Noteworthy in RESTful Web Services API - Arun Gupta
JAX-RS 2.0: New and Noteworthy in RESTful Web Services API - Arun GuptaJAX-RS 2.0: New and Noteworthy in RESTful Web Services API - Arun Gupta
JAX-RS 2.0: New and Noteworthy in RESTful Web Services API - Arun Gupta
 
Developing web-apps like it's 2013
Developing web-apps like it's 2013Developing web-apps like it's 2013
Developing web-apps like it's 2013
 
Ajax - a quick introduction
Ajax - a quick introductionAjax - a quick introduction
Ajax - a quick introduction
 
Ad java prac sol set
Ad java prac sol setAd java prac sol set
Ad java prac sol set
 

Dernier

Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DaySri Ambati
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 

Dernier (20)

Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 

RESTfull with RestKit

  • 1. RESTfull iOS with RestKit Taras Kalapun
  • 3. 3
  • 4. RestKit is a RESTful Object Mapping Framework for Cocoa - (void)loadData { RKObjectManager* objectManager = [RKObjectManager sharedManager]; RKObjectMapping* 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); } - (void)objectLoader:(RKObjectLoader*)objectLoader didFailWithError:(NSError*)error { NSLog(@"Hit error: %@", error); } 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 • RKParams - Multi-part MIME requests • Reachability - Detecting of ine/online status 7
  • 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]; } 8
  • 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]); } 9
  • 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]); } } 10
  • 11. Requests with Parameters - (void)sendRequestWithParams { // Simple params NSDictionary* paramsDictionary = [NSDictionary dictionaryWithObjectsAndKeys: @"Taras Kalapun", @"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]; } 11
  • 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!"); } } 12
  • 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 14
  • 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", } 15
  • 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]; 17
  • 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"]; 18
  • 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); } 19
  • 20. Con guring the Router - (void)configureRouter { [objectManager.router routeClass:[Contact class] toResourcePath:@"/contacts/(contactID)"]; [objectManager.router routeClass:[Contact class] toResourcePath:@"/contacts" forMethod:RKRequestMethodPOST]; } 20
  • 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]; } 21
  • 22. Core Data 22
  • 23. Con guring 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"]; } 23
  • 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]; 24
  • 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]; 25
  • 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]; 26
  • 27. Integration Points Three20 Ruby on Rails 27
  • 28. http://restkit.org/ http://twitter.com/restkit http://github.com/RestKit/RestKit
  • 29. ? Taras Kalapun iOS dev, Team lead, it-specialist t.kalapun@gmail.com Skype: t.kalapun

Notes de l'éditeur

  1. \n
  2. RestKit is an Objective-C framework for iOS that aims to make interacting with RESTful web services simple, fast and fun. It combines a clean, simple HTTP request/response API with a powerful object mapping system that reduces the amount of code you need to write to get stuff done.\n\nRestKit&apos;s primary goal is to allow the developer to think more in terms of their application&apos;s data model and worry less about the details of sending requests, parsing responses, and building representations of remote resources.\n
  3. \n
  4. \n
  5. \n
  6. A simple, high level HTTP request / response system.\nRestKit ships with an HTTP client built on top of NSURLConnection and provides a library of helpful methods for inspecting MIME types and status codes. Submitting form data is as simple as providing a dictionary of parameters and a native params object is included for easily creating multi-part submissions.\n
  7. Framework level support for switching servers &amp; environments (development/production/staging).\nRestKit uses a base URL and resource paths rather than full URL&amp;#x2019;s to allow you to switch target servers quickly. Interpolating URL strings and constructing NSURL objects is a thing of the past.\n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. RestKit provides a modeling layer for mapping processed data payloads into native Cocoa objects declaratively. This lets the application programmer stop worrying about parsing and simply ask the framework to asynchronously fetch a remote resource and call the delegate with the results. Object mapping is implemented using key-value coding, allowing for quick traversal of the parsed object graph. Reflection is used on the property types to allow for mapping from remote dates encoded as a string back to NSDate objects.\n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. Building on top of the object mapping layer, RestKit provides integration with Apple&amp;#x2019;s Core Data framework. This support allows RestKit to persist remotely loaded objects directly back into a local store, either as a fast local cache or a primary data store that is periodically synced with the cloud. RestKit can populate Core Data associations for you, allowing natural property based traversal of your data model. It also provides a nice API on top of the Core Data primitives that simplifies configuration and querying use cases.\n
  23. \n
  24. \n
  25. \n
  26. When the Core Data object store is used, you can seed a database from a collection of data files. This lets you submit your apps to the App Store with a database in the app bundle that is ready for immediate use.\n
  27. \n
  28. \n
  29. \n