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
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
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
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
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's primary goal is to allow the developer to think more in terms of their application'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 & environments (development/production/staging).\nRestKit uses a base URL and resource paths rather than full URL&#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&#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