RestKit - description of one of the features

Hi Habr!

Background



I noticed for a long time that there is not a single article on the Haber about such a wonderful library as RestKit , written in Objective-C and providing excellent opportunities for working with RESTful services. Therefore, the idea came up to publish a brief description of some of the library's features, especially since a completely new version of it has already been released, using the AFNetworking library as a basis for working with HTTP. The article describes one of the most important functionalities for me - object mapping.

The library installation process is described in detail on the project page on GitHub. Also access library in Pods:
$ cat Podfile
platform :ios, '5.0'
pod 'RestKit', '~> 0.20.0pre'

Let's get down to business


We can do without theory, because the article is still for those who understand, at least, what REST is and why it is needed.

Initialization


When starting the application, it is necessary to set the initial parameters for singletones working with HTTP and mapping objects:
NSURL *baseURL = [NSURL URLWithString:kServerHost];
AFHTTPClient* client = [[AFHTTPClient alloc] initWithBaseURL:baseURL];
RKObjectManager *objectManager = [[RKObjectManager alloc] initWithHTTPClient:client];
[RKObjectManager setSharedManager:objectManager];


Mapping objects

First, we need to describe the class in which the data will be stored (where it will be mapped):
@interface TaskListSuccess : NSObject
@property(nonatomic, copy) NSString *created_at;
@property(nonatomic, copy) NSString *updated_at;
@property(nonatomic, copy) NSString *user_id;
@property(nonatomic, copy) NSString *ID;
@property(nonatomic, copy) NSString *title;
@property(nonatomic, copy) NSString *time;
@end

Next, you need to add a rule for answers for what requests this class will be used and by what rule objects are mapped:
RKObjectMapping* successAuthResult = [RKObjectMapping mappingForClass:[TaskListSuccess class]];
[successAuthResult addAttributeMappingsFromDictionary:@{ 
     // задаются ассоциации полей JSON(XML) к параметрам класса
     @"created_at": @"created_at",
     @"updated_at": @"updated_at",
     @"user_id": @"user_id",
     @"id": @"ID",
     @"title": @"title",
     @"time": @"time",
}];
// Набор статус-кодов, при которых запрос является успешно выполненым.
NSIndexSet *successStatusCodes = RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful); 
RKResponseDescriptor 
           *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:successAuthResult
                                                                      pathPattern:@"tasks"
                                                                            keyPath:nil
                                                                     statusCodes:successStatusCodes];
[[RKObjectManager sharedManager] addResponseDescriptor:responseDescriptor];

The pathPattern parameter of the RKResponseDescriptor class describes the path template for which our class will be used for mapping.
Next, you need to send the request itself:
RKObjectManager *objectManager = [RKObjectManager sharedManager];
[objectManager getObject:nil 
                   path:@"tasks" 
                   parameters:nil 
                   success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
       //Тут происходит обработка данных
       ...
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
       //Тут необходимо обрабатывать ошибки
       ...
}];

This is the simplest request, sometimes we need more flexibility in customizing the request, then we can do it, for example, as follows:
RKObjectManager *objectManager = [RKObjectManager sharedManager];
NSMutableURLRequest *urlRequest = [objectManager requestWithObject:nil 
                                  method:RKRequestMethodPOST 
                                  path:@"tasks"
                                  parameters:nil];
[urlRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
RKObjectRequestOperation *operation = [objectManager objectRequestOperationWithRequest:urlRequest 
                      success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
       //Тут происходит обработка данных
       ...
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
       //Тут необходимо обрабатывать ошибки
       ...
}];
[objectManager enqueueObjectRequestOperation:operation];

An object of class RKObjectRequestOperation contains all the possible parameters that we can set as we like.

Outro


This article is for guidance only and is aimed at understanding whether it is relevant to describe this library further, especially since there is very good documentation in English. In general, if this topic is of interest, then it will be possible to return to it and describe other possibilities of the library, as well as talk about personal bumps filled during its use.

Should I describe the library further?

Opportunities:
  • work with CoreData
  • work with multi-page requests (pagination)
  • Mapping using multiple entities in one request is more complicated
  • and etc.


All the best! World!

Also popular now: