I am trying to call web service and upload image,
There is a problem in the mapping, and I have spent many hours on it without success. The error I am getting is:
Error Domain=org.restkit.RestKit.ErrorDomain Code=1001 "No mappable
object representations were found at the key paths searched."
UserInfo={NSLocalizedDescription=No mappable object representations
were found at the key paths searched., NSLocalizedFailureReason=The
mapping operation was unable to find any nested object representations
at the key paths searched: user The representation inputted to the
mapper was found to contain nested object representations at the
following key paths: message, success This likely indicates that you
have misconfigured the key paths for your mappings., keyPath=null,
DetailedErrors=( )}
and there method that call web service
[SVProgressHUD show];
[delegate.objectManager.HTTPClient.defaultHeaders setValue:#"application/x-www-form-urlencoded" forKey:#"content-type" ];
RKObjectMapping *responseMapping = [RKObjectMapping mappingForClass:[SignUpResponse class]]; //create response and request mapping
[responseMapping addAttributeMappingsFromDictionary:#{#"phone": #"phone",
#"device_type": #"device_type",
#"device_token": #"device_token",
#"type": #"type",
#"email": #"email",
#"identity": #"identity",
#"date": #"date",
#"status": #"status",
#"name": #"name",
#"activation": #"activation",
#"image": #"image",
#"id": #"id"
}];
RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:responseMapping
method:RKRequestMethodPOST
pathPattern:#"AgentRegister"
keyPath:#"user"
statusCodes:[NSIndexSet indexSetWithIndex:200]];
[delegate.objectManager.defaultHeaders setValue:#"application/x-www-form-urlencoded" forKey:#"content-type" ];
delegate.objectManager.requestSerializationMIMEType =RKMIMETypeFormURLEncoded;
[delegate.objectManager removeResponseDescriptor:responseDescriptor];
[delegate.objectManager addResponseDescriptor:responseDescriptor];
NSString *fcmToken = [FIRInstanceID instanceID].token;
SignUpRequest *signUpRequest = [[SignUpRequest alloc]init];
signUpRequest.phone = txtPhoneNumber.text;
signUpRequest.email = txtEmail.text;
signUpRequest.identity=txtIdOrCity.text;
signUpRequest.device_type=#"IOS";
signUpRequest.device_token=fcmToken;
signUpRequest.type=#"1";
UIImage *image = [UIImage imageNamed:#"Logo"];
// Serialize the Article attributes then attach a file
NSMutableURLRequest *request = [[RKObjectManager sharedManager] multipartFormRequestWithObject:signUpRequest method:RKRequestMethodPOST path:#"AgentRegister" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:UIImagePNGRepresentation(image)
name:#"image"
fileName:#"photo.png"
mimeType:#"application/x-www-form-urlencoded"];
}];
RKObjectRequestOperation *operation = [[RKObjectManager sharedManager] objectRequestOperationWithRequest:request success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult){
[SVProgressHUD dismiss];
if(mappingResult.array.count !=0){
[self performSegueWithIdentifier:#"goToVerify" sender:self];
}else{
}
[delegate.objectManager removeResponseDescriptor:responseDescriptor];
}failure:^(RKObjectRequestOperation *operation, NSError *error){
[SVProgressHUD dismiss];
NSLog(#"%#",error.description);
UIAlertController *alert = [UIAlertController alertControllerWithTitle:#".."
message:#"حدث خطاء ما .. حاول مرة اخري" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *okAction = [UIAlertAction actionWithTitle:#"Ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
}];
[alert addAction:okAction];
[self presentViewController:alert animated:YES completion:nil];
[delegate.objectManager removeResponseDescriptor:responseDescriptor];
}];
[[RKObjectManager sharedManager] enqueueObjectRequestOperation:operation];
}
This error is telling you that nothing was available at the user path. For instance, if your response is JSON, there would be no root key called user, only message and success:
{
"user": "<- This key doesnt exist",
"message": "<- There is something here",
"success": "<- There is also something here"
}
You most likely need to change your keyPath from user to something like success.user.
Related
This is my JSON: link
This is my Mapper:
-(RKObjectManager *)mapContact{
RKObjectMapping* dataMapping = [RKObjectMapping mappingForClass:[Data class]];
[dataMapping addAttributeMappingsFromDictionary:#{
#"Data": #"app_data",
#"message": #"app_message",
#"status":#"app_status",
#"Success": #"app_success"
}];
RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:dataMapping method:RKRequestMethodGET pathPattern:nil keyPath:#"" statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
RKEntityMapping* contactMapping = [RKEntityMapping mappingForEntityForName:#"Contact" inManagedObjectStore:managedObjectStore];
contactMapping.identificationAttributes = #[#"con_id"];
[contactMapping addAttributeMappingsFromDictionary:#{
#"content": #"con_content",
#"id" : #"con_id",
#"title" : #"con_title",
#"language":#"con_language",
}];
RKResponseDescriptor *responseDescriptor2 = [RKResponseDescriptor responseDescriptorWithMapping:contactMapping
method:RKRequestMethodGET
pathPattern:nil
keyPath:#"data.contentblock"
statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
NSArray *arrResponsDescriptor = [[NSArray alloc]initWithObjects:responseDescriptor,responseDescriptor2,nil];
[objectManager addResponseDescriptorsFromArray:arrResponsDescriptor];
return objectManager;
}
And this is my webservice call:
-(void)fetchContactOnCompletion:(myCompletion) compblock{
Mapper *mapper = [Mapper new];
RKManagedObjectStore *store = [[ASLDataModel sharedDataModel] objectStore];
NSManagedObjectContext *context = store.mainQueueManagedObjectContext;
RKObjectManager *objectManager = [mapper mapContact];
NSString *urlString = [NSString stringWithFormat:#"webservice/content/get/apikey/%#/language/%#/contentid/2",apikey,language];
NSURLRequest *request = [objectManager requestWithObject:nil method:RKRequestMethodGET path:urlString parameters:nil];
RKManagedObjectRequestOperation *operation = [objectManager managedObjectRequestOperationWithRequest:request managedObjectContext:context success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
Data *data = [mappingResult.dictionary valueForKey:#""];
if([data.app_status isEqualToNumber:#200]){
NSError *error = nil;
BOOL success = [context save:&error];
if (!success) RKLogWarning(#"Failed saving managed object context: %#", error);
NSError *saveError = nil;
compblock(YES);
}else{
compblock(NO);
}
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
}];
[objectManager enqueueObjectRequestOperation:operation];
}
And I get these errors:
2015-09-08 08:38:56.431 ASLTravel[17377:427756] D restkit.object_mapping:RKMapperOperation.m:433 Finished performing object mapping. Results: (null)
2015-09-08 08:38:56.432 ASLTravel[17377:427753] E restkit.network:RKObjectRequestOperation.m:209 GET 'http://asl-travel.be/webservice/content/get/apikey/asl001/language/nl/contentid/2' (200 OK / 0 objects) [request=1.6674s mapping=0.0000s total=1.6899s]:
error=Error Domain=org.restkit.RestKit.ErrorDomain Code=1001 "No response descriptors match the response loaded." UserInfo=0x7f9413f8b730 {NSLocalizedFailureReason=A 200 response was loaded from the URL 'http://www.asl-travel.be/webservice/content/get/apikey/asl001/language/nl/contentid/2', which failed to match all (2) response descriptors:
<RKResponseDescriptor: 0x7f9413f535e0 baseURL=http://asl-travel.be/ pathPattern=(null) statusCodes=200-299> failed to match: response URL 'http://www.asl-travel.be/webservice/content/get/apikey/asl001/language/nl/contentid/2' is not relative to the baseURL 'http://asl-travel.be/'.
<RKResponseDescriptor: 0x7f9413f2b1e0 baseURL=http://asl-travel.be/ pathPattern=(null) statusCodes=200-299> failed to match: response URL 'http://www.asl-travel.be/webservice/content/get/apikey/asl001/language/nl/contentid/2' is not relative to the baseURL 'http://asl-travel.be/'., NSErrorFailingURLStringKey=http://www.asl-travel.be/webservice/content/get/apikey/asl001/language/nl/contentid/2, NSErrorFailingURLKey=http://www.asl-travel.be/webservice/content/get/apikey/asl001/language/nl/contentid/2, NSUnderlyingError=0x7f9413c2fc20 "No mappable object representations were found at the key paths searched.", keyPath=null, NSLocalizedDescription=No response descriptors match the response loaded.}
Can anyone please help me with this? I'm searching for this problem for hours now...
Many thanks !
The web service is redirecting you to www.asl-travel.be so the pattern matcher will never find a match. Update the base URL or turn off the redirection to fix this.
I'm receiving a dictionary from my restkit request as respond but only one of values are included. I am missing bunch of KV from my JSON.
JSON response from API:
{"categories" : [
{
"status" : 1,
"rest_id" : 1,
"id" : 1,
"title" : "01. BasicC",
"description" : "basic description"
},
{
"status" : 1,
"rest_id" : 1,
"id" : 26,
"title" : "01. Deli",
"description" : "deli description"
}
]}
IOS Function to request:
- (void)loadProduct{
_categoriesDic=[[NSDictionary alloc]init];
RKObjectMapping* productMapping = [RKObjectMapping mappingForClass:[ProductCategory class]];
[productMapping addAttributeMappingsFromDictionary:#{
#"id": #"id",
#"rest_id": #"rest_id",
#"title": #"title",
#"description": #"description",
#"status":#"status"
}];
RKLogConfigureByName("RestKit/Network", RKLogLevelTrace);
RKLogConfigureByName("RestKit/ObjectMapping", RKLogLevelTrace);
RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:productMapping method:RKRequestMethodPOST pathPattern:nil keyPath:#"categories" statusCodes:[NSIndexSet indexSetWithIndex:200]];
RKObjectManager *objectManager = [[RKObjectManager alloc] init];
[objectManager addResponseDescriptor:responseDescriptor];
NSString *jsonRequest = [NSString stringWithFormat:#"id=1"];
NSURL *url=[NSURL URLWithString:#"http://example.com/REST/v2/productCategories"];
NSData *json_data = [NSData dataWithBytes:[jsonRequest UTF8String] length:[jsonRequest length]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setHTTPBody: json_data];
RKObjectRequestOperation *objectRequestOperation = [[RKObjectRequestOperation alloc] initWithRequest:request responseDescriptors:#[ responseDescriptor ]];
[objectRequestOperation setCompletionBlockWithSuccess:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
RKLogInfo(#"Load collection of Categories: %#", mappingResult.dictionary);
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
RKLogError(#"Operation failed with error: %#", error);
}];
[objectRequestOperation start];
}
response:
Load collection of Categories: {
categories = (
"basic description",
"deli description"
);
}
While your code does some slightly odd things (like create an empty immutable dictionary, and POST to an endpoint which should be using a GET) it does appear to work. It looks like you just aren't fully understanding the response, and that's because you are inadvertently overriding a built in method.
The log you show contains:
{
categories = (
"basic description",
"deli description"
);
}
is the description of a dictionary which contains 1 key (categories), which is an array of 2 objects. Now, those 2 objects have their description method called as well in order to generate the log contents. Unfortunately, you have a property called description so that is accessed instead of the superclass implementation., and hence you just get the descriptions.
Now, that doesn't mean the mapping hasn't worked, just that the log is misleading.
You should change the description on your destination object to another name, like overview and then your log will be meaningful (and you won't see similar issues in future).
I have an API that I'm querying where when I query for a list of organizations I get an array of:
{
id: integer,
name: string
}
But I am also able to get details on each organization which returns a single object like:
{
id: integer,
name: string,
description: text,
visit_count: integer,
image_url: string
}
How would I set up the object(s) in RestKit for this?
You need to setup the following:
The Object with all the elements you described in your second block
An object manager
RKObjectManager *objectManager = [RKObjectManager managerWithBaseURL:[NSURL URLWithString:YOUR HOST NAME]];
objectManager.requestSerializationMIMEType=RKMIMETypeJSON;
A mapping object with all the elements in your object
RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[YOUR CLASS class]];
The mapping for your object
[mapping addAttributeMappingsFromArray:#[#"id",
#"name",
#"description",
#"visit_count",
#"image_url"
]];
A response descriptor
RKResponseDescriptor *responseDesciptor = [RKResponseDescriptor responseDescriptorWithMapping:mapping method:RKRequestMethodAny pathPattern:OBJECT URL keyPath:YOUR KEY PATH statusCodes:nil];
Add the response descriptor to the object manager
[objectManager responseDesciptor];
Now you can hit up the server
[[RKObjectManager sharedManager] postObject:nil path:OBJECT URL parameters:nil
success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
self.variable = [NSMutableArray arrayWithArray: mappingResult.array];
}
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"An Error Has Occurred" message:[error localizedDescription] delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
}];
RestKitObjectMapping Array off null objects
I want to map CapitalImage object in Capital images object property.
//------------------------ The mapping I try to
[RKMIMETypeSerialization registerClass:[RKNSJSONSerialization class]
forMIMEType:#"text/html"];
RKObjectMapping *CapitalImageMap = [RKObjectMapping mappingForClass:[CapitalImage class]];
[CapitalImageMap addAttributeMappingsFromDictionary:#{
#"src": #"src"
}];
RKObjectMapping *CapitalMap = [RKObjectMapping mappingForClass:[Capital class]];
[CapitalMap addAttributeMappingsFromDictionary:#{
#"name": #"name",
#"text": #"text"
}];
[CapitalMap addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:#"images" toKeyPath:#"images" withMapping:CapitalImageMap]];
NSIndexSet *statusCodes = RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful);
RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:CapitalMap
method:RKRequestMethodAny
pathPattern:nil
keyPath:nil
statusCodes:statusCodes];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://www.a10073.de4.dp10.ru/icapitals/capital.php"]];
RKObjectRequestOperation *operation = [[RKObjectRequestOperation alloc] initWithRequest:request responseDescriptors:#[responseDescriptor]];
[operation setCompletionBlockWithSuccess:^(RKObjectRequestOperation *operation, RKMappingResult *result) {
Capital *article = [result firstObject];
NSLog(#"Mapped the article: %# , %#", article.name,article.images.description);
} failure:^(RKObjectRequestOperation *operation, NSError *error) { NSLog(#"Failed with error: %#", [error localizedDescription]); }];
[operation start];
I get this result
2013-09-27 23:20:49.028 iCapitals v2[5099:c07] Mapped the article: London , (
(null),
(null),
(null),
)
LOGS - http://www.a10073.de4.dp10.ru/icapitals/consoleresult.txt
Please check the code and tell what i do wrong, Thanks!!!
Your mappings look correct. The log shows the mapping proceeding correctly. The issue appears to be with the CapitalImage class. Why is it giving a nil description? It could be that that is the only problem. So your log of the array is a list of nil, but the objects do exist.
Try logging the src of each objects. Are you seeing other issues? Did you implement the description method?
I am trying to integrate RestKit 0.20 to My Project So for Example i am using google rss reader for sample project.
This is the response for Xml
/
/category>
&
This is the Xml from where i have to get the data.
RKObjectMapping* articleMapping = [RKObjectMapping mappingForClass:[News class]];
[articleMapping addAttributeMappingsFromDictionary:#{
#"title": #"title",
#"link": #"link",
#"guid": #"guid",
#"pubDate": #"pubDate",
#"description": #"description"
}];
NSURL* url = [[NSURL alloc]initWithString:#"http://news.google.com"];
RKObjectManager* objectManager = [RKObjectManager managerWithBaseURL:url];
NSURLRequest* request = [objectManager requestWithObject:nil method:RKRequestMethodGET path:#"/?output=rss" parameters:nil];
RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:articleMapping pathPattern:nil keyPath:#"item" statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
RKObjectRequestOperation *objectRequestOperation = [[RKObjectRequestOperation alloc] initWithRequest:request responseDescriptors:#[ responseDescriptor ]];
[objectRequestOperation setCompletionBlockWithSuccess:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
RKLogInfo(#"Load collection of Articles: %#", mappingResult.array);
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
RKLogError(#"Operation failed with error: %#", error);
}];
[objectRequestOperation start];
Above is the code i used to get data When i run the app i am getting the following error
I restkit.network:RKObjectRequestOperation.m:174 GET 'http://news.google.com/?output=rss'
2013-05-28 12:24:15.076 TestApp[8940:15203] E restkit.network:RKObjectRequestOperation.m:569 Object request failed: Underlying HTTP request operation failed with error: Error Domain=org.restkit.RestKit.ErrorDomain Code=-1016 "Expected content type {(
"application/xml",
"application/x-www-form-urlencoded",
"application/json"
)}, got application/rss+xml" UserInfo=0xa80a3d0 {NSLocalizedRecoverySuggestion=NFE/1.0Top Stories - Google News
Can any one help
As the exception says, RestKit is expecting one of:
"application/xml"
"application/x-www-form-urlencoded"
"application/json"
But it's receiving "application/rss+xml". You just need to tell RestKit what to expect.
You can ask RestKit if it already understands the mime type:
[RKMIMETypeSerialization registeredMIMETypes];
If not you'll need to register a serializer with RKMIMETypeSerialization.
And you can tell the object manager what mime type to expect:
[objectManager setAcceptHeaderWithMIMEType:#"application/rss+xml"];