RESTfull iOS with RestKit            Taras Kalapun
What is RestKit?                   2
3
RestKit is a RESTful Object Mapping Framework                    for Cocoa- (void)loadData {   RKObjectManager* objectMana...
RestKit Architecture        • Network Layer        • Object Mapping        • Core Data        • Pluggable parsing layer   ...
Network Layer                6
Key Concepts• RKClient - Your user agent• Base URLs and Resource Paths• RKRequest & RKResponse - The HTTP  lifecycle• RKPa...
Initializing RKClient- (void)initRKClient {   // Initialize with a Base URL   RKClient* client = [RKClient clientWithBaseU...
Sending Requests- (void)sendRequest {   // Send an HTTP GET request to http://restkit.org/contacts   [[RKClient sharedClie...
Processing Responses- (void)sendRequest {   // Send an HTTP GET request to http://restkit.org/contacts   [[RKClient shared...
Requests with Parameters- (void)sendRequestWithParams {   // Simple params   NSDictionary* paramsDictionary = [NSDictionar...
Reachability- (void)demoReachability {   // Check if the network is available   [[RKClient sharedClient] isNetworkAvailabl...
Object Mapping 2.0                     13
Modeling a RESTful Service         "user": {            "id":31337,            "name":"Blake Watters",            "screen_...
"created_at":"Sat Mar 05 13:39:09 +0000 2011","favorited":false,"id":44029179364253700,"in_reply_to_screen_name":"JustJenF...
Initializing the Object Mapping                                  16
// Init RestKitRKObjectManager* objectManager = [RKObjectManagerobjectManagerWithBaseURL:@"http://twitter.com"];// Setup o...
// Setup our object mappingsRKObjectMapping* statusMapping = [RKObjectMapping mappingForClass:[RKTStatus class]];[statusMa...
Loading Remote Objects- (void)loadTimeline {   // Load the object model via RestKit   RKObjectManager* objectManager = [RK...
Con guring the Router- (void)configureRouter {   [objectManager.router routeClass:[Contact class] toResourcePath:@"/contac...
RESTful Object Manipulation// Create a new Contact- (void)createObject {    Contact* contact = [Contact new];    contact.n...
Core Data            22
Con guring CoreData#import <RestKit/CoreData/CoreData.h>- (void)configureObjectStore {  // Initialize the RestKit Object M...
MappingRKManagedObjectMapping* userMapping = [RKManagedObjectMappingmappingForEntityWithName:@"RKTUser"];userMapping.prima...
Working with Core Data// Adapted from https://github.com/magicalpanda/MagicalRecord// Get all the ContactsNSArray* contact...
Database SeedingNSString *seedDatabaseName = nil;NSString *databaseName = RKDefaultSeedDatabaseFileName;objectManager.obje...
Integration PointsThree20              Ruby on Rails                              27
http://restkit.org/        http://twitter.com/restkithttp://github.com/RestKit/RestKit
?Taras KalapuniOS dev, Team lead, it-specialistt.kalapun@gmail.comSkype: t.kalapun
Upcoming SlideShare
Loading in …5
×

RESTfull with RestKit

20,520 views

Published on

Published in: Technology, Design
0 Comments
28 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
20,520
On SlideShare
0
From Embeds
0
Number of Embeds
80
Actions
Shares
0
Downloads
336
Comments
0
Likes
28
Embeds 0
No embeds

No notes for slide
  • \n
  • 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
  • \n
  • \n
  • \n
  • 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
  • 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
  • \n
  • \n
  • \n
  • \n
  • \n
  • 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
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • 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
  • \n
  • \n
  • \n
  • 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
  • \n
  • \n
  • \n
  • RESTfull with RestKit

    1. 1. RESTfull iOS with RestKit Taras Kalapun
    2. 2. What is RestKit? 2
    3. 3. 3
    4. 4. RestKit is a RESTful Object Mapping Framework for Cocoa- (void)loadData { RKObjectManager* objectManager = [RKObjectManager sharedManager]; RKObjectMapping* statusMapping = [objectManager.mappingProviderobjectMappingForKeyPath:@"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. 5. RestKit Architecture • Network Layer • Object Mapping • Core Data • Pluggable parsing layer • Integration Points 5
    6. 6. Network Layer 6
    7. 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. 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. 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. 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. 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([UIImageimageNamed:@"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. 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
    13. 13. Object Mapping 2.0 13
    14. 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. 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 andreach out if you need any support!","user":{ "id":208727870, "name":"RestKit", "screen_name":"RestKit", } 15
    16. 16. Initializing the Object Mapping 16
    17. 17. // Init RestKitRKObjectManager* objectManager = [RKObjectManagerobjectManagerWithBaseURL:@"http://twitter.com"];// Setup our object mappingsRKObjectMapping* userMapping = [RKObjectMapping mappingForClass:[RKTUserclass]];[userMapping mapKeyPath:@"id" toAttribute:@"userID"];[userMapping mapKeyPath:@"screen_name" toAttribute:@"screenName"];[userMapping mapAttributes:@"name", nil]; 17
    18. 18. // Setup our object mappingsRKObjectMapping* 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. 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 theappropriate object mapping if ([objectManager.acceptMIMEType isEqualToString:RKMIMETypeJSON]) { statusMapping = [objectManager.mappingProviderobjectMappingForKeyPath:@"status"]; } [objectManager loadObjectsAtResourcePath:@"/status/user_timeline/RestKit"objectMapping:statusMapping delegate:self];}- (void)objectLoader:(RKObjectLoader*)objectLoader didLoadObjects:(NSArray*)objects { NSLog(@"Loaded statuses: %@", objects);} 19
    20. 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. 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. 22. Core Data 22
    23. 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 = [RKManagedObjectStoreobjectStoreWithStoreFilename:@"Contacts.sqlite"];} 23
    24. 24. MappingRKManagedObjectMapping* userMapping = [RKManagedObjectMappingmappingForEntityWithName:@"RKTUser"];userMapping.primaryKeyAttribute = @"userID";[userMapping mapKeyPath:@"id" toAttribute:@"userID"];[userMapping mapKeyPath:@"screen_name" toAttribute:@"screenName"];[userMapping mapAttributes:@"name", nil]; 24
    25. 25. Working with Core Data// Adapted from https://github.com/magicalpanda/MagicalRecord// Get all the ContactsNSArray* contacts = [Contact allObjects];// Count the ContactsNSError* error = nil;NSUInteger count = [Contact count:&error];// Find Contact by primary keyNSNumber* contactID = [NSNumber numberWithInt:12345];Contact* somebody = [Contact objectWithPrimaryKeyValue:contactID];// Find Contacts with criteriaNSPredicate* predicate = [NSPredicate predicateWithFormat:@"name contains[cd] restkit"];NSArray* matches = [Contact objectsWithPredicate:predicate]; 25
    26. 26. Database SeedingNSString *seedDatabaseName = nil;NSString *databaseName = RKDefaultSeedDatabaseFileName;objectManager.objectStore = [RKManagedObjectStoreobjectStoreWithStoreFilename:databaseName usingSeedDatabaseName:seedDatabaseNamemanagedObjectModel:nil delegate:self];RKManagedObjectSeeder* seeder = [RKManagedObjectSeederobjectSeederWithObjectManager: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. 27. Integration PointsThree20 Ruby on Rails 27
    28. 28. http://restkit.org/ http://twitter.com/restkithttp://github.com/RestKit/RestKit
    29. 29. ?Taras KalapuniOS dev, Team lead, it-specialistt.kalapun@gmail.comSkype: t.kalapun

    ×