RKObjectManager sharedManager getObjectsAtPath Optionally save in persistent storage - ios

[[RKObjectManager sharedManager] getObjectsAtPath:#"/pathpattern/:userId" parameters:nil success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
NSLog(#"success");
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
NSLog(#"fail");
}];
I am using RKManagedObjectStore using addSQLitePersistentStoreAtPath:fromSeedDatabaseAtPath:withConfiguration:options:error
The defined pattern gives different data for different "userId", I want to save data in sqlite data base for only one userId, for other userIds I don't want to save it.
Any suggestion how this could be achieved using same [RKObjectManager sharedManager]

You can use an RKDynamicMapping with the response descriptor for that path. With that mapping you can analyse the incoming data and decide which mapping you actually want to apply to the received data.
Note that 'not saving' the new objects to Core Data means using an RKObjectMapping instead of RKEntityMapping.

you don`t init your shared manager. try this.
NSURL *url = [NSURL URLWithString:yourURL];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
RKObjectManager *operation = [[RKObjectManager alloc] initWithHTTPClient:httpClient];
[[RKObjectManager sharedManager] getObjectsAtPath:kURLToDownloadData
parameters:nil
success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult){
NSLog(#"success");
}
failure:^(RKObjectRequestOperation *operation, NSError *error) {
NSLog(#"fail");
}

Related

Restkit metadata isn't mapping

I'm struggling to get proper mapping with metadata... Everything maps perfectly except metadata url parameters.
Here's my Entity Mapping :
RKEntityMapping *statisticsMapping = [RKEntityMapping mappingForEntityForName:#"Statistics" inManagedObjectStore:managedObjectStore];
[statisticsMapping addAttributeMappingsFromArray:#[#"fromDate", #"toDate", #"visits", #"newVisits"]];
[statisticsMapping addAttributeMappingsFromDictionary:#{
#"#metadata.routing.parameters.randomId" : #"applicationRandomId"
}];
[statisticsMapping addConnectionForRelationship:#"application" connectedBy:#"applicationRandomId"];
Response descriptor:
RKResponseDescriptor *ststResp = [RKResponseDescriptor responseDescriptorWithMapping:statisticsMapping
method:RKRequestMethodGET
pathPattern:#"api/apps/:randomId/statistics"
keyPath:#"details"
statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
Routing:
[objectManager.router.routeSet addRoute:[RKRoute routeWithClass:[Statistics class] pathPattern:#"api/apps/:randomId/statistics" method:RKRequestMethodGET]];
And how I get them:
NSString *url = [NSString stringWithFormat:#"/api/apps/%#/statistics",applicationRandomId];
NSMutableURLRequest *statistics = [[RKObjectManager sharedManager] requestWithObject:#"Statistics" method:RKRequestMethodGET path:url parameters:#{
#"fromDate" : #"01-01-2016",
#"toDate" : #"20-01-2016"
}];
RKObjectRequestOperation *operation = [[RKObjectManager sharedManager] managedObjectRequestOperationWithRequest:statistics managedObjectContext:[RKManagedObjectStore defaultStore].mainQueueManagedObjectContext success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
}];
I also tried mix with variety of Routes and getObjectsAt etc...
Regards, Adrian.
Solution :
[objectManager.router.routeSet addRoute:[RKRoute routeWithName:#"statistics" pathPattern:#"api/apps/:randomId/statistics" method:RKRequestMethodGET]];
[[RKObjectManager sharedManager] getObjectsAtPathForRouteNamed:#"statistics" object:#{#"randomId" : applicationRandomId} parameters:nil
} success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
}];
Eh didn't know it works that way.

iOS RestKit loggging doesn't print anything

I would like to user RestKit's network logging with the following code:
RKLogConfigureByName("RestKit/Network", RKLogLevelTrace);
I am creating GET/POST requests and nothing is printed to the console. I am using Xcode 6.1.1.
Anybody has any clues why it isn't printing anything to the console?
Edit:
RestKit initialization:
RKLogConfigureByName("RestKit/Network", RKLogLevelTrace);
[RKObjectManager setSharedManager:[RKObjectManager managerWithBaseURL:self.baseURL]];
[[RKObjectManager sharedManager] setAcceptHeaderWithMIMEType:RKMIMETypeJSON];
[RKObjectManager sharedManager].requestSerializationMIMEType = RKMIMETypeJSON;
RKManagedObjectStore *managedObjectStore = [[RKManagedObjectStore alloc] initWithPersistentStoreCoordinator:[IPCoreDataHelper sharedInstance].persistentStoreCoordinator];
[managedObjectStore createManagedObjectContexts];
[RKManagedObjectStore setDefaultStore:managedObjectStore];
[RKObjectManager sharedManager].managedObjectStore = [RKManagedObjectStore defaultStore];
[self setMappings];
After this, for example, the user will press the login button and the following code is executed
Login:
// ... Setup the user object
NSMutableURLRequest *urlRequest = [[RKObjectManager sharedManager] requestWithObject:user method:RKRequestMethodPOST path:#"login/" parameters:nil];
urlRequest.timeoutInterval = 300;
RKManagedObjectRequestOperation *operation = [[RKObjectManager sharedManager] managedObjectRequestOperationWithRequest:urlRequest managedObjectContext:[RKManagedObjectStore defaultStore].mainQueueManagedObjectContext success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
// Do something with login success
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
// Failed
}];
[operation start];

Reskit - callback on the same thread instead of UI thread

I am performing getObjectsAtPath in a background thread. However, the success/failure blocks are called on the UI thread.
Is there a way to force RestKit to call success and failure blocks on the same thread instead on the UI thread?
Restkit does not provide this functionality, but you can archive this.
RKObjectRequestOperation class has two properties successCallbackQueue & failureCallbackQueue, which are allows you to set call back queue. Overwrite RKObjectManager class and return RKObjectRequestOperation then you can set callback queues.
- (RKObjectRequestOperation *)getObjectsAtPath:(NSString *)path
parameters:(NSDictionary *)parameters
success:(void (^)(RKObjectRequestOperation *operation, RKMappingResult *mappingResult))success
failure:(void (^)(RKObjectRequestOperation *operation, NSError *error))failure
{
NSParameterAssert(path);
RKObjectRequestOperation *operation = [self appropriateObjectRequestOperationWithObject:nil method:RKRequestMethodGET path:path parameters:parameters];
[operation setCompletionBlockWithSuccess:success failure:failure];
[self enqueueObjectRequestOperation:operation];
return operation;
}
Then you can set callback queues as shown bellow:
RKObjectManager *objectManager = [RKObjectManager sharedManager];
RKObjectRequestOperation *operation = [objectManager getObjectsAtPath:path
parameters:parameters
success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
}
failure:^(RKObjectRequestOperation *operation, NSError *error) {
}];
operation.successCallbackQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0);
operation.failureCallbackQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0);

Post JSON Body + MultiPart RestKit 0.2x fails

I am trying to post an object with an attached file.
NSMutableURLRequest *request =
[objectManager multipartFormRequestWithObject:reqDocObj
method:RKRequestMethodPOST
path:#"syncDocument.json"
parameters:nil
constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:UIImagePNGRepresentation([UIImage imageNamed:#"graybox.png"])
name:#"image"
fileName:#"some_file"
mimeType:#"image/jpeg"];
}];
RKObjectRequestOperation *operation =
[objectManager
objectRequestOperationWithRequest:request
success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
}
failure:^(RKObjectRequestOperation *operation, NSError *error) {
NSLog(#"WS: errore operazione di richiesta %#",error);
}
];
[objectManager enqueueObjectRequestOperation:operation];
The objectManager is configured as:
[objectManager setAcceptHeaderWithMIMEType:RKMIMETypeJSON];
[objectManager setRequestSerializationMIMEType:RKMIMETypeJSON];
objectManager.requestSerializationMIMEType = RKMIMETypeJSON;
[EDIT]
My mapepd object is SynchDocObj:
requestDocMapping = [RKObjectMapping mappingForClass:[SynchDocObj class]];
[requestDocMapping addAttributeMappingsFromDictionary:mappingDocDict];
The problem is:
1) In the RKlogs, the request.body = null and the JSON object is put into the form-data
2) The server cannot decode the body because it is null
My question is:
1) Am I sending the JSON object in the wrong way?
2) If yes, how can I send a JSON object with a file upload, i.e. as a multipart request?
Regards!
[SOLUTION]
Following the suggestion of the answer, I think the solution is 1) retrieve the mapped object from the form-data and not the body ; 2) OR post a nil object and putting a JSON string within the form-data.
This:
[objectManager setRequestSerializationMIMEType:RKMIMETypeJSON];
objectManager.requestSerializationMIMEType = RKMIMETypeJSON;
is 2 different ways of saying the same thing - and you don't want to have either of them. You need to send the request as form URL encoded (the default value).
The easiest thing to do is to use the same form as in your current code to create the request, generate the JSON earlier and then use appendPartWithFormData:name: to add it to the request (just before you add the file).
To generate the JSON you can use RestKit (RKMappingOperation) or you can just create a dictionary / array of content and then use NSJSONSerialization to serialise that object to be added to the request.
Analyze my code, it works like a charm:
RKRequestDescriptor *requestDescriptor = [RKRequestDescriptor requestDescriptorWithMapping:[FilledExamCard defineMapping] objectClass:[MappedClassName class] rootKeyPath:nil method:RKRequestMethodPUT];
NSData *jsonPayload = [self getJSONpayloadFromObject:mappedClassObject requestDescriptor:requestDescriptor];
NSURL *baseURL = [NSURL URLWithString:[ZDR_BASE_URL stringByAppendingString:#"PutExamCards"]];
AFHTTPClient *client = [AFHTTPClient clientWithBaseURL:baseURL];
[RKMIMETypeSerialization registerClass:[RKNSJSONSerialization class] forMIMEType:#"text/plain"];
[client setDefaultHeader:#"Accept" value:#"text/plain"];
RKObjectManager *objectManager = [[RKObjectManager alloc] initWithHTTPClient:client];
[objectManager setRequestSerializationMIMEType: RKMIMETypeJSON];
[objectManager addRequestDescriptor:requestDescriptor];
NSMutableURLRequest *request = [objectManager multipartFormRequestWithObject:nil method:RKRequestMethodPUT path:#"" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
// Name may vary depending from server settings
[formData appendPartWithFormData:jsonPayload name:#"model"];
}];
RKObjectRequestOperation *operation = [objectManager objectRequestOperationWithRequest:request success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
// Process data
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
// An error occurred
}];
-(NSData*)getJSONpayloadFromObject:(NSObject*)object requestDescriptor:(RKRequestDescriptor*)requestDescriptor
{
NSDictionary *paramObject = [RKObjectParameterization parametersWithObject:object requestDescriptor:requestDescriptor error:nil];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:paramObject options:NSJSONWritingPrettyPrinted error:&error];
return jsonData;
}

iOS multipart form request failing with attempt to insert nil object from objects[1]

Trying to do a multipart form request with Restkit and I am getting and NSdictionary error? I am not sure why am getting this error.
[__NSPlaceholderDictionary initWithObjects:forKeys:count:]: attempt to insert nil object from objects[1]'
NSMutableURLRequest *request = [[RKObjectManager sharedManager] multipartFormRequestWithObject:obj
method:RKRequestMethodPOST path:#"v1/things/update_avatar.json"
parameters:#{
#"auth_token" : self.accessToken,
#"email" : user.userID,
#"api_key" : self.api_key,
#"avatar" : #"userAvatar"
}
constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:UIImageJPEGRepresentation(image, 1)
name:#"obj[image]"
fileName:#"userAvatar.jpeg"
mimeType:#"image/jpeg"];
}];
RKObjectRequestOperation *operation = [[RKObjectManager sharedManager] objectRequestOperationWithRequest:request
success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
//
DLog(#"");
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
//
DLog(#"");
}];
[[RKObjectManager sharedManager] enqueueObjectRequestOperation:operation]; // NOTE: Must be enqueued rather than started
It may be one of these self.accessToken, user.userID and self.api_key is nil.
Use NSParameterAssert to check those parameter in debug mode

Resources