RestKit - Updating existing object from another RKObjectManager - ios

I have 2 RKObjectManager that configured to use same managedObjectStore.
With the first RKObjectManager I fetch list of objects, and with the second RKObjectManager I want to add data to these objects.
But instead of updating existing objects, new ones are created.
What am I missing?
Here is my code:
RKEntityMapping* serverAppMapping = [RKEntityMapping mappingForEntityForName:#"COApp" inManagedObjectStore:[RKObjectManager coopsiManager].managedObjectStore];
[serverAppMapping addAttributeMappingsFromDictionary:#{
#"id": #"coID"
}];
serverAppMapping.identificationAttributes = #[ #"coID" ];
RKResponseDescriptor *serverAppResponseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:serverAppMapping method:RKRequestMethodGET pathPattern:#"/me/apps" keyPath:#"data.items" statusCodes:[NSIndexSet indexSetWithIndex:200]];
RKEntityMapping *appsMapping = [RKEntityMapping mappingForEntityForName:#"COApp" inManagedObjectStore:[RKObjectManager coopsiManager].managedObjectStore];
[appsMapping addAttributeMappingsFromDictionary:#{
#"trackName": #"name",
#"trackId": #"coID",
#"artworkUrl60":#"imageURL"}];
appsMapping.identificationAttributes = #[ #"coID" ];
[serverAppMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:#"app"
toKeyPath:#"app"
withMapping:appsMapping]];
// register mappings with the provider using a response descriptor
RKResponseDescriptor *appResponseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:appsMapping method:RKRequestMethodGET pathPattern:#"/th/lookup" keyPath:#"results" statusCodes:[NSIndexSet indexSetWithIndex:200]];
[[RKObjectManager appleManager] addResponseDescriptor:appResponseDescriptor];
[[RKObjectManager coopsiManager] addResponseDescriptor:serverAppResponseDescriptor];
NSString* access_token = [[COAuthManager sharedInstance] getUserAccessToken];
NSDictionary *queryParams;
queryParams = [NSDictionary dictionaryWithObjectsAndKeys:access_token, #"access_token", nil];
[[RKObjectManager coopsiManager] getObjectsAtPath:#"/me/apps" parameters:queryParams success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
NSOrderedSet* set = [NSOrderedSet orderedSetWithArray:mappingResult.array];
[me addNewApps:set];
self.objects = [me.newApps mutableCopy];
[self.delegate dataRefrashed];
NSManagedObjectContext *moc = [[RKObjectManager coopsiManager]managedObjectStore].persistentStoreManagedObjectContext;
NSError *error;
if (![moc save:&error]) {
NSLog(#"Fail");
}else{
NSLog(#"luda rest kit objetcs - %#",me.newApps);
}
for (COApp * app in self.objects) {
NSDictionary *queryParams = [NSDictionary dictionaryWithObjectsAndKeys:app.coID, #"id", nil];
[[RKObjectManager appleManager] getObjectsAtPath:[NSString stringWithFormat:#"/th/lookup"] parameters:queryParams success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
// app.app = mappingResult.array[0];
[self.delegate dataRefrashed];
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
[self presentError:error];
}];
}
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
[self presentError:error];
}];

Related

restkit mapping nested array is empty (nested restkit request with json response)

Am i doing something weired here ?
my categories get downloaded and mapped,
product also get downloaded and mapped as logging is saying,
but my products are empty under each category,
thnx!
{
"productsCategories" : [
{
"product" : [
{
"price" : 3.99,
"title" : "Product A"
},
{
"price" : 3.99,
"title" : "ProductB "
}
],
"categoryTitle" : “a category“
}
]
}
RKObjectMapping *productCategoryMapping = [RKObjectMapping mappingForClass:[ProductCategory class]];
[productCategoryMapping addAttributeMappingsFromDictionary:#{
#"categoryTitle": #"tit"
}];
RKObjectMapping* productMapping = [RKObjectMapping mappingForClass:[Product class] ];
[productMapping addAttributeMappingsFromDictionary:#{
#"title": #"tit",
#"price": #"prc"
}];
[productCategoryMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:#"product"
toKeyPath:#"product"
withMapping:productMapping]];
RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:productCategoryMapping method:RKRequestMethodPOST pathPattern:#"productByCategory" keyPath:#"productsCategories" statusCodes:[NSIndexSet indexSetWithIndex:200]];
NSURL *url=[NSURL URLWithString:#"http://www.example.com/REST/v2/"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
RKObjectManager *manager = [RKObjectManager managerWithBaseURL:url];
[manager addResponseDescriptor:responseDescriptor];
NSMutableDictionary *mutableParameters = [NSMutableDictionary dictionary];
[mutableParameters setValue:#"1" forKey:#"id"];
[manager addResponseDescriptor:[RKResponseDescriptor responseDescriptorWithMapping:productCategoryMapping method:RKRequestMethodPOST pathPattern:#"productByCategory" keyPath:#"productsCategories" statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)]];
[manager postObject:request path:#"productByCategory" parameters:mutableParameters success:^(RKObjectRequestOperation *operation, RKMappingResult *result){
self.productCategoryArr=result.array;
[self.tblDetails reloadData];
}failure:^(RKObjectRequestOperation *operation, NSError *error) {
RKLogError(#"Operation failed with error: %#", error);
self.productCategoryArr=nil;
}];
the logging says objects are being mapped for each products but I only get
ProductCategory: 0x7bf53510
ProductCategory: 0x7be57f00
arrays and 0 objects in each
Assuming your ProductCategory class has
NSArray *Product
NSString * tit
Create a top level RKObjectMapping like,
RKObjectMapping * ProductCategoryResponseMapping = [RKObjectMapping mappingForClass: [ProductCategoryResponse class]];
[ProductCategoryResponseMapping addAttributeMappingsFromDictionary:#{
#"productsCategories": #"productsCategories"
}];
And create new class ProductCategoryResponse which should have
NSArray * productsCategories
Use ProductCategoryResponseMapping for Response descriptor.
Now your response will have array of productsCategories, each having array of Products and String tit.

RKMappingresult returning different result in 64-bit iphones with restkit

I have a strange problem with Restkit. I'm doing the following:
-(void)doLogin:(NSString *)email andPassword:(NSString *)password OnCompletion:(myCompletion) compblock{
Mapper *mapper = [Mapper new];
RKManagedObjectStore *store = [[OffitelDataModel sharedDataModel] objectStore];
NSLog(#"store is %#",store);
NSManagedObjectContext *context = store.mainQueueManagedObjectContext;
RKObjectManager *objectManager = [mapper mapLogin];
NSString *deviceToken = [[NSUserDefaults standardUserDefaults]objectForKey:#"deviceToken"];
NSString *urlString = [NSString stringWithFormat:#"company-user/login/%#?email=%#&pwd=%#&ios_id=%#",apikey,email,password,deviceToken];
NSURLRequest *request = [objectManager requestWithObject:nil method:RKRequestMethodGET path:urlString parameters:nil];
RKManagedObjectRequestOperation *operation = [objectManager managedObjectRequestOperationWithRequest:request managedObjectContext:context success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
NSError *error = nil;
BOOL success = [context save:&error];
if (!success) RKLogWarning(#"Failed saving managed object context: %#", error);
Data *data2 = [mappingResult.array objectAtIndex:0];
NSLog(#"MAPPING RESULT 0 = %#",[mappingResult.array objectAtIndex:0]);
NSLog(#"data status is %#",data2.webstatus);
int value = [data2.webstatus intValue];
if (value == 200){
Person *personObject = [mappingResult.array objectAtIndex:2];
NSString *name = [NSString stringWithFormat:#"%# %#",personObject.cu_first_name,personObject.cu_last_name];
NSDictionary *dictUser = [[NSDictionary alloc]initWithObjectsAndKeys:personObject.cu_id,#"personId",personObject.company.c_id,#"companyId",name,#"personName",personObject.cu_status_id,#"statusId", nil];
[[NSUserDefaults standardUserDefaults]setObject:dictUser forKey:#"user"];
[[NSUserDefaults standardUserDefaults]setObject:[NSNumber numberWithBool:YES] forKey:#"loggedIn"];
[[NSUserDefaults standardUserDefaults] synchronize];
compblock(YES);
}else{
//show validation
NSLog(#"ERROR");
}
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
NSLog(#"ERROR");
}];
[objectManager enqueueObjectRequestOperation:operation];
}
En this is my mapping
-(RKObjectManager *)mapLogin{
RKObjectMapping* dataMapping = [RKObjectMapping mappingForClass:[Data class]];
[dataMapping addAttributeMappingsFromDictionary:#{
#"status": #"webstatus",
#"message": #"message",
#"text": #"text"
}];
RKEntityMapping* personMapping = [RKEntityMapping mappingForEntityForName:#"Person" inManagedObjectStore:managedObjectStore];
personMapping.identificationAttributes = #[#"cu_id"] ;
[personMapping addAttributeMappingsFromDictionary:#{
#"cu_id": #"cu_id",
#"cu_status_id": #"cu_status_id",
#"cu_company_id": #"cu_company_id",
#"cu_function_id": #"cu_function_id",
#"cu_department_id": #"cu_department_id",
#"cu_email": #"cu_email",
#"cu_first_name": #"cu_first_name",
#"cu_last_name": #"cu_last_name",
#"cu_phone_intern": #"cu_phone_intern",
#"cu_mobile_phone": #"cu_mobile_phone",
#"cu_street": #"cu_street",
#"cu_number": #"cu_number",
#"cu_bus": #"cu_bus",
#"cu_postalcode": #"cu_postalcode",
#"cu_location": #"cu_location",
#"cu_country": #"cu_country",
#"cu_birthdate": #"cu_birthdate",
#"cu_picture": #"cu_picture",
#"cu_comment": #"cu_comment",
#"cu_ison_reminder_email": #"cu_ison_reminder_email",
#"cu_ison_reminder_app": #"cu_ison_reminder_app",
#"cu_ison_reminder_web": #"cu_ison_reminder_web",
#"cu_first_use": #"cu_first_use"
}];
RKEntityMapping* functionMapping = [RKEntityMapping mappingForEntityForName:#"Function" inManagedObjectStore:managedObjectStore];
functionMapping.identificationAttributes = #[#"cf_id"] ;
[functionMapping addAttributeMappingsFromDictionary:#{
#"cf_id": #"cf_id",
#"cf_name":#"cf_name"
}];
RKEntityMapping* departmentMapping = [RKEntityMapping mappingForEntityForName:#"Department" inManagedObjectStore:managedObjectStore];
departmentMapping.identificationAttributes = #[#"cd_id"] ;
[departmentMapping addAttributeMappingsFromDictionary:#{
#"cd_id": #"cd_id",
#"cd_name":#"cd_name"
}];
RKEntityMapping* companyMapping = [RKEntityMapping mappingForEntityForName:#"Company" inManagedObjectStore:managedObjectStore];
companyMapping.identificationAttributes = #[#"c_id"] ;
[companyMapping addAttributeMappingsFromDictionary:#{
#"c_id": #"c_id",
#"c_name":#"c_name",
#"c_phone":#"c_phone",
#"c_fax":#"c_fax",
#"c_website":#"c_website"
}];
RKEntityMapping* statusMapping = [RKEntityMapping mappingForEntityForName:#"Status" inManagedObjectStore:managedObjectStore];
statusMapping.identificationAttributes = #[#"cs_id"] ;
[statusMapping addAttributeMappingsFromDictionary:#{
#"cs_id": #"cs_id",
#"cs_company_id":#"cs_company_id",
#"cs_name":#"cs_name",
#"cs_default":#"cs_default",
#"cs_image":#"cs_image"
}];
RKRelationshipMapping* relationFunctionMapping = [RKRelationshipMapping relationshipMappingFromKeyPath:#"function"toKeyPath:#"function"withMapping:functionMapping];
RKRelationshipMapping* relationDepartmentMapping = [RKRelationshipMapping relationshipMappingFromKeyPath:#"department"toKeyPath:#"department"withMapping:departmentMapping];
RKRelationshipMapping* relationCompanyMapping = [RKRelationshipMapping relationshipMappingFromKeyPath:#"company"toKeyPath:#"company"withMapping:companyMapping];
RKRelationshipMapping* relationStatusMapping = [RKRelationshipMapping relationshipMappingFromKeyPath:#"statuses"toKeyPath:#"status"withMapping:statusMapping];
[personMapping addPropertyMapping:relationFunctionMapping];
[personMapping addPropertyMapping:relationDepartmentMapping];
[personMapping addPropertyMapping:relationCompanyMapping];
[companyMapping addPropertyMapping:relationStatusMapping];
RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:dataMapping
pathPattern:nil
keyPath:#"data" statusCodes:[NSIndexSet indexSetWithIndex:200]];
RKResponseDescriptor *responseDescriptor2 = [RKResponseDescriptor responseDescriptorWithMapping:personMapping
pathPattern:nil
keyPath:#"data.user"
statusCodes:[NSIndexSet indexSetWithIndex:200]];
RKResponseDescriptor *responseDescriptor3 = [RKResponseDescriptor responseDescriptorWithMapping:companyMapping
pathPattern:nil
keyPath:#"data.user.company"
statusCodes:[NSIndexSet indexSetWithIndex:200]];
NSArray *arrResponsDescriptor = [[NSArray alloc]initWithObjects:responseDescriptor,responseDescriptor2,responseDescriptor3, nil];
[objectManager addResponseDescriptorsFromArray:arrResponsDescriptor];
return objectManager;
}
The strange this is that on most phones it all works correct but only on 64-bit devices are going wrong.
When I look at this NSLog
NSLog(#"MAPPING RESULT 0 = %#",[mappingResult.array objectAtIndex:0]);
I see that in the not-64-bit devices it returns the Data class object. And thats oké. But in the 64-bit devices it returns the Company-object and that's not ok !
Can somebody help me with this ?
Kind regards
You have multiple response descriptors each with a nil path pattern, so they will always be applied to any response. RestKit does not guarantee the order in which they will be called. It also doesn't guarantee the order of the contents of mappingResult.array.
You should be using your key paths on the response descriptors to access the results of each descriptor. The mappingResult also offers you a dictionary (instead of array) where you can use the response descriptor key path to access the associated results. Use that to separate the Data results from the Company results.

this class is not key value coding-compliant for the key Text using RestKit v0.20.0

For 2 days now, I've been trying to find out why I'm getting the error using iOS 6.1.3 with Xcode 4.6.2 and RestKit 0.20.0:
"...this class is not key value coding-compliant for the key Text."
The strange part is that I can receive (GET) the JSON object fine. The error happens when I create my sample SignalMessage object and then try to PUT it back to the server.
The JSON is as follows:
{"Text":"New Message","HasMessage":"true"}
The SignalMessage object looks like this:
#import <Foundation/Foundation.h>
#interface SignalMessage : NSObject {
}
#property (nonatomic, copy) NSString *signalText;
#property (nonatomic, retain) NSNumber *isHasMessage;
#end
And the implementation like this:
#import "SignalMessage.h"
#implementation SignalMessage
#synthesize isHasMessage, signalText;
#end
My correctly working getMessage function looks like this:
- (IBAction)getMessage:(id)sender;
{
NSLog(#"%#", #"Getting message... ");
NSURL *url = [NSURL URLWithString:#"http://ec2-54-243-148-145.compute-1.amazonaws.com/TabletPractice/api/signal?clientIdentifier=2"];
RKObjectManager *manager = [RKObjectManager managerWithBaseURL:url];
RKObjectMapping *responseMapping = [RKObjectMapping mappingForClass:[SignalMessage class]];
[responseMapping addAttributeMappingsFromDictionary:#{#"Text":#"signalText", #"HasMessage": #"isHasMessage"}];
RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:responseMapping pathPattern:nil keyPath:nil statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
[manager addResponseDescriptor:responseDescriptor];
[manager getObject:nil path:#"" parameters:nil success:^(RKObjectRequestOperation *operation, RKMappingResult *result)
{
NSArray *theresults = [result array];
for (SignalMessage *item in theresults) {
self.txtMessage.text = item.signalText;
[self hideControls];
}
} failure:^(RKObjectRequestOperation * operation, NSError * error)
{
NSLog (#"Server WS call failure: operation: %# \n\nerror: %#", operation, error);
}];
}
And here is the sendClicked message that gives me grieve:
- (IBAction)btnSendClicked:(id)sender;
{
if ([txtMessage.text length] < 1)
return;
NSURL *url = [NSURL URLWithString:#"http://ec2-54-243-148-145.compute-1.amazonaws.com/TabletPractice/api/signal?clientIdentifier=2"];
RKObjectManager *manager = [RKObjectManager managerWithBaseURL:url];
RKObjectMapping *requestMapping = [RKObjectMapping requestMapping];
[requestMapping addAttributeMappingsFromDictionary:#{#"Text":#"signalText", #"HasMessage": #"isHasMessage"}];
RKRequestDescriptor *requestDescriptor = [RKRequestDescriptor requestDescriptorWithMapping:requestMapping
objectClass:[SignalMessage class]
rootKeyPath:#""];
[manager addRequestDescriptor:requestDescriptor];
SignalMessage *newMessage = [[SignalMessage alloc] init];
newMessage.signalText = #"Test Message";
BOOL isMsg = TRUE;
NSNumber *boolAsNumber = [NSNumber numberWithBool:isMsg];
newMessage.isHasMessage = boolAsNumber;
[manager putObject:newMessage path:#"" parameters:nil success:^(RKObjectRequestOperation *operation, RKMappingResult *result) {
NSLog(#"We object mapped the response with the following result: %#", result);
} failure:^(RKObjectRequestOperation * operation, NSError * error)
{
NSLog (#"Server WS call failure: operation: %# \n\nerror: %#", operation, error);
}];
[self hideControls];
}
At this point, I'm at a loss.
Please add a inverse mapping to your RKRequestDescriptor in your btnSendClicked method like below:
RKRequestDescriptor *requestDescriptor = [RKRequestDescriptor
requestDescriptorWithMapping:[requestMapping inverseMapping]
objectClass:[SignalMessage class]
rootKeyPath:#""];

Restkit mapping one to many

I have mapping like this:
RKObjectMapping *pageMapping = [RKEntityMapping mappingForEntityForName:#"Page" inManagedObjectStore:[RKManagedObjectStore defaultStore]];
[pageMapping addAttributeMappingsFromArray:#[ #"rows, columns", #"header", #"size", #"backgroundColor" ]];
RKObjectMapping *objectMapping = [RKEntityMapping mappingForEntityForName:#"Object" inManagedObjectStore:[RKManagedObjectStore defaultStore]];
[objectMapping addAttributeMappingsFromArray:#[ #"content", #"crop", #"fontName", #"fontSize", #"height", #"width",
#"paddingLeft", #"paddingTop", #"paddingRight", #"paddingBottom", #"src", #"textColor", #"type", #"url", #"posX", #"posY" ]];
[objectMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:#"objects" toKeyPath:#"objects" withMapping:pageMapping]];
RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:pageMapping pathPattern:nil keyPath:#"pages" statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
[[RKObjectManager sharedManager] addResponseDescriptor:responseDescriptor];
[[RKObjectManager sharedManager] getObjectsAtPath:[magazine contentPath]
parameters:nil
success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
[self sortPageResult];
Page *page = (Page *)[self.pagesFetchedResultController objectAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
NSLog(#"%d", [[page objects] count]);
//[self changeStatusToDownloaded:[magazine magazineID]];
[self.collectionView reloadData];
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
[self displayError];
NSLog(#"Product error: %#", [error localizedDescription]);
[self.collectionView reloadData];
}];
And I've got a problem with mapping. I clearly map "page" object, but I can't map "object". When I try it I get something like this:
Relationship 'objects' fault on managed object (0x1d8b57a0) <Page: 0x1d8b57a0> (entity: Page; id: 0x1d8b0740 <x-coredata://30A44191-D972-4222-88DF-539C2875F293/Page/p1> ; data: {
backgroundColor = FFFFFF;
columns = 0;
content = nil;
header = 1;
link = nil;
magazine = nil;
margin = 0;
objects = "<relationship fault: 0x1d8aea40 'objects'>";
pageID = nil;
rows = 0;
size = 1;
})
Thx for reply!
New progress
I've changed:
[objectMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:#"objects" toKeyPath:#"objects" withMapping:pageMapping]];
instead:
[pageMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:#"items" toKeyPath:#"items" withMapping:itemMapping]];
Now is mapping right, but mapping causing duplicating "object" entities. There's only one object, which is remaking again and again :/

RestKit: How to batch multiple requests and get a response once they finish?

I just found out RestKit and it will be an important part of the app I'm doing. At the time, I was able to integrate it with the core data, but have not figured out the best way to send multiple GET requests.
What I need to do is:
Get data from the following addresses:
http://url.com/api/banner/
http://url.com/api/category/
http://url.com/api/link/
The URL will always be in the following format: http://url.com/api/SOMETHING/
Once all requests are finished, I would like to run a code (such as calling a new view controller). What would be the best way to do this?
At the moment, this is the code I'm using:
- (id)init
{
self = [super init];
if (self) {
[self setupConnector];
[self setupDatabase];
[self setupMappings];
[self sendRequests];
}
return self;
}
- (void)setupConnector
{
// Initialize RestKIT
RKObjectManager *objectManager = [RKObjectManager managerWithBaseURL:[NSURL URLWithString:#"http://baseURL"]];
self.managedObjectStore = [[RKManagedObjectStore alloc] initWithManagedObjectModel:[[NLCoreData shared] managedObjectModel]];
objectManager.managedObjectStore = self.managedObjectStore;
}
- (void)setupDatabase
{
NSString *storePath = [[NLCoreData shared] storePath];
NSError *error = nil;
NSPersistentStore *persistentStore = [self.managedObjectStore addSQLitePersistentStoreAtPath:storePath fromSeedDatabaseAtPath:nil withConfiguration:nil options:nil error:&error];
NSAssert(persistentStore, #"Failed to add persistent store with error: %#", error);
[self.managedObjectStore createManagedObjectContexts];
self.managedObjectStore.managedObjectCache = [[RKInMemoryManagedObjectCache alloc] initWithManagedObjectContext:self.managedObjectStore.persistentStoreManagedObjectContext];
}
- (void)setupMappings
{
RKObjectManager *objectManager = [RKObjectManager sharedManager];
// Mappings
// banner
RKEntityMapping *bannerMapping = [RKEntityMapping mappingForEntityForName:#"Banner" inManagedObjectStore:self.managedObjectStore];
[bannerMapping addAttributeMappingsFromDictionary:#{
#"title": #"title",
#"id": #"bannerID",
#"created_at": #"created_at",
#"image": #"image",
#"resource_uri": #"resource_uri",
#"updated_at": #"updated_at",
#"url": #"url"
}];
bannerMapping.identificationAttributes = #[ #"bannerID" ];
RKResponseDescriptor *bannerDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:bannerMapping
pathPattern:#"/api/v1/banner/"
keyPath:#"objects"
statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
[objectManager addResponseDescriptor:bannerDescriptor];
// category
RKEntityMapping *categoryMapping = [RKEntityMapping mappingForEntityForName:#"Category" inManagedObjectStore:self.managedObjectStore];
[categoryMapping addAttributeMappingsFromDictionary:#{
#"name": #"name",
#"id": #"categoryID",
#"created_at": #"created_at",
#"resource_uri": #"resource_uri",
#"updated_at": #"updated_at",
#"active": #"active"
}];
categoryMapping.identificationAttributes = #[ #"categoryID" ];
RKResponseDescriptor *categoryDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:categoryMapping
pathPattern:#"/api/v1/category/"
keyPath:#"objects"
statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
[objectManager addResponseDescriptor:categoryDescriptor];
}
- (void)sendRequests
{
RKObjectManager *objectManager = [RKObjectManager sharedManager];
// Send Request
[objectManager getObjectsAtPath:#"/api/v1/banner/" parameters:nil success:^(RKObjectRequestOperation * operation, RKMappingResult *mappingResult) {
NSLog(#"SUCCESS: %#", mappingResult.array);
} failure: ^(RKObjectRequestOperation * operation, NSError * error) {
NSLog(#"FAILURE %#", error);
}];
// category
[objectManager getObjectsAtPath:#"/api/v1/category/" parameters:nil success:^(RKObjectRequestOperation * operation, RKMappingResult *mappingResult) {
NSLog(#"SUCCESS: %#", mappingResult.array);
} failure: ^(RKObjectRequestOperation * operation, NSError * error) {
NSLog(#"FAILURE %#", error);
}];
}
Any tips?
The RestKit solution would be this: instead of using the convenience method ObjectManager::getObjectsAtPath you will have to init all of your RKObjectRequestOperations manually and then use ObjectManager::enqueueBatchOfObjectRequestOperations:progress:completion: method to enqueue them.
Alternatively, and I think this is actually easier and cleaner solution, use dispatch groups as described in the accepted answer to this question.
NSURL *url1 = [NSURL URLWithString:#"http://baseURL.domain/api/banner/"];
NSMutableURLRequest *request2 = [NSMutableURLRequest requestWithURL:url1];
RKObjectRequestOperation *objectRequestOperation1 = [[RKObjectRequestOperation alloc] initWithRequest:request2 responseDescriptors:#[ ResponseDescriptor ]];
NSURL *url2 = [NSURL URLWithString:#"http://baseURL.domain/api/category/"];
NSMutableURLRequest *request2 = [NSMutableURLRequest requestWithURL:url2];
RKObjectRequestOperation *objectRequestOperation2 = [[RKObjectRequestOperation alloc] initWithRequest:request2 responseDescriptors:#[ ResponseDescriptor ]];
NSArray *requestArray = [NSArray arrayWithObjects:objectRequestOperation,objectRequestOperation1,objectRequestOperation2, nil];
[[RKObjectManager sharedManager] enqueueBatchOfObjectRequestOperations:requestArray progress:^(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations) {
//
// Handle process indicator
//
NSLog(#"%lu",(unsigned long)totalNumberOfOperations);
} completion:^(NSArray *operations) {
//
// Remove blocking dialog, do next tasks
?

Resources