I'm struggling to even get basic stuff working in restkit. I am an experienced developer too which makes it even more frustrating.
I have successfully have it posting a json object to my service and via debugging through the RestKit source I have verified that the desired json has been returned. It returns to the success block but with nothing except an empty object.
Here is my code that sets up the mappings and launches the request.
Note: I have obscured some sensitive passwords/urls.
RKObjectMapping *requestMapping = [RKObjectMapping requestMapping];
[requestMapping addAttributeMappingsFromDictionary:#{ #"DeviceKey": #"DeviceKey", #"DeviceName": #"DeviceName", #"Password": #"Password", #"Username": #"Username"}];
RKRequestDescriptor *requestDescriptor = [RKRequestDescriptor requestDescriptorWithMapping:requestMapping
objectClass:[LoginRequest class]
rootKeyPath:nil];
RKObjectMapping *responseMapping = [RKObjectMapping mappingForClass:[LoginResponse class]];
responseMapping.forceCollectionMapping = YES;
[responseMapping addAttributeMappingsFromDictionary:#{#"TotalBalance":#"TotalBalance",#"FirstName":#"FirstName"}];
RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:responseMapping
pathPattern:#"Login"
keyPath:nil
statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
RKObjectManager *manager = [RKObjectManager managerWithBaseURL:[NSURL URLWithString:#"http://api.test.com/account/"]];
[manager addRequestDescriptor:requestDescriptor];
[manager addResponseDescriptor:responseDescriptor];
manager.requestSerializationMIMEType = RKMIMETypeJSON;
LoginRequest *request = [[LoginRequest alloc] init];
request.DeviceKey = #"xxxxxxx";
request.DeviceName = #"iPhone";
request.Username = #"mike";
request.Password = #"******";
[manager postObject:request path:#"Login" parameters:nil success:^(RKObjectRequestOperation *operation, RKMappingResult *result) {
NSArray * array = [result array];
NSDictionary * dictionary = [result dictionary];
NSObject * obj = [result firstObject];
NSLog(#"We object mapped the response with the following result: %#", result);
// It ends up in the success callback but all of these are EMPTY :(
} failure:^(RKObjectRequestOperation *operation, NSError *err){
NSLog(#"We had a problemo");
}];
LogonResponse.h (the .m simply synthisizes them properties)
#import <Foundation/Foundation.h>
#interface LoginResponse : NSObject
#property(nonatomic,assign) double TotalBalance;
#property(nonatomic,retain) NSString * FirstName;
#end
The JSON:
{
"TotalBalance":22.34,
"FirstName":"Mike"
........ other stuff but this shouldn't matter
}
The console is showing:
2013-06-26 14:03:07.173 Tests.com[1666:907] I restkit.support:RKMIMETypeSerialization.m:115 JSON Serialization class 'RKNSJSONSerialization' detected: Registering for MIME Type 'application/json
2013-06-26 14:03:07.181 Tests.com[1666:3907] T restkit.network:RKHTTPRequestOperation.m:139 POST 'http://api.test.com/account/Login':
request.headers={
Accept = "application/json";
"Accept-Language" = "en-GB, en, fr, de, ja, nl, it, es, pt, pt-PT, da, fi, nb, sv, ko, zh-Hans, zh-Hant, ru, pl, tr, uk, ar, hr, cs, el, he, ro, sk, th, id, ms, ca, hu, vi, en-us;q=0.8";
"Content-Type" = "application/json; charset=utf-8";
"User-Agent" = "Tests.com/2.10.31_dev (iPad; iOS 6.1.3; Scale/1.00)";
}
request.body={"DeviceKey":"xxxxxxx","DeviceName":"iPhone","Password":"******","Username":"mike"}
2013-06-26 14:03:07.297 Tests.com[1666:162f] D restkit.network:RKHTTPRequestOperation.m:191 Received authentication challenge
2013-06-26 14:03:08.016 Tests.com[1666:162f] T restkit.network:RKHTTPRequestOperation.m:156 POST 'http://api.test.com/account/Login' (200):
response.headers={
"Content-Length" = 1172;
"Content-Type" = "application/json; charset=utf-8";
Date = "Wed, 26 Jun 2013 04:03:04 GMT";
Server = "Microsoft-IIS/7.5";
Vary = "Accept-Encoding";
"X-Powered-By" = "ASP.NET";
}
response.body={"CustomerReference":"50713881","FirstName":"Mike","TotalBalance":22.25,"ErrorInfo":null,"Success":true}
2013-06-26 14:03:08.021 Tests.com[1666:3b13] W restkit.object_mapping:RKMapperOperation.m:76 Adding mapping error: Cannot map a collection of objects onto a non-mutable collection. Unexpected destination object type 'LoginRequest'
(lldb)
Why is it going on about LoginRequest?? I'm so lost!!
Any help would be very much appreciated.
When you make a post request with RestKit, I believe the mapper tries to map the response to the same object type that was sent. In this case, because a LoginRequest was sent it wants to map the response to a LoginRequest object.
A solution to this might be to create a temporary LoginResponse object and post that with a dictionary containing your login request fields (username, password, etc.). That way, RestKit will be able to map the response into the temporary object that you created.
Upgrading to v0.20.3 fixed this issue.
Related
I am reviving an old project that originally used RestKit 0.10, and now am using RestKit 0.24. The old version still works, but unfortunately RestKit 0.10 is not 64-bit compatible and hence does not submit to the AppStore (and it is certainly time to update anyway).
I cannot get an object to post correctly. In RestKit 0.10, properties without values were not sent to the server, whereas it seems in RestKit 0.20 they are. I have tried explicitly setting assignsDefaultValueForMissingAttributes to NO, but it doesn't seem to make a difference.
The server expects the following format:
{"response": {"assessment_id":"1","time_taken":"60"},
"answer": [
{"question_number": 1, "answer_value": 3},
{"question_number": 2, "answer_value": 2},
{"question_number": 3, "answer_value": 1},
]
}
I have set up an object CompletedAssessment which contains a Response object and an array of Answer objects. (Note that when these objects are received from the server, many more properties need to be received than need to be sent).
#interface CompletedAssessment : NSObject {
Response *response;
NSArray *answers;
}
#interface Answer : NSObject {
NSNumber *identifier;
NSNumber *responseId;
NSNumber *questionNumber;
NSString *answerHistory;
NSString *answerValue;
NSString *answerText;
NSNumber *timeTaken;
}
#interface Response : NSObject {
NSNumber *identifier;
NSNumber *assessmentId;
NSNumber *timeTaken;
NSNumber *clientId;
NSString *assessmentShortName;
NSString *score;
NSString *interpretation;
NSString *dateCreated;
NSString *localTime;
}
I set the mapping up as follows:
RKObjectMapping *answerMapping = [RKObjectMapping mappingForClass:[Answer class]];
answerMapping.assignsDefaultValueForMissingAttributes = NO;
[answerMapping addAttributeMappingsFromDictionary:#{
#"id": #"identifier",
#"response_id": #"responseId",
#"question_number": #"questionNumber",
#"answer_history": #"answerHistory",
#"answer_value": #"answerValue",
#"answer_text": #"answerText",
#"time_taken": #"timeTaken"
}];
RKObjectMapping *responseMapping = [RKObjectMapping mappingForClass:[Response class]];
responseMapping.assignsDefaultValueForMissingAttributes = NO;
[responseMapping addAttributeMappingsFromDictionary:#{
#"id": #"identifier",
#"client_id": #"clientId",
#"assessment_id": #"assessmentId",
#"time_taken": #"timeTaken",
#"score": #"score",
#"assessment_short_name": #"assessmentShortName",
#"interpretation": #"interpretation",
#"created": #"dateCreated",
#"local_time": #"localTime"
}];
RKObjectMapping *completedAssessmentMapping = [RKObjectMapping mappingForClass:[CompletedAssessment class]];
completedAssessmentMapping.assignsDefaultValueForMissingAttributes = NO;
[completedAssessmentMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:#"response" toKeyPath:#"response" withMapping:responseMapping]];
[completedAssessmentMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:#"answer" toKeyPath:#"answers" withMapping:answerMapping]];
RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:completedAssessmentMapping method:RKRequestMethodGET pathPattern:nil keyPath:#"data.completedAssessment" statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
[[RKObjectManager sharedManager] addResponseDescriptor:responseDescriptor];
RKRequestDescriptor *requestDescriptor = [RKRequestDescriptor requestDescriptorWithMapping:[completedAssessmentMapping inverseMapping] objectClass:[CompletedAssessment class] rootKeyPath:nil method:RKRequestMethodPOST];
[[RKObjectManager sharedManager] addRequestDescriptor:requestDescriptor];
[objectManager.router.routeSet addRoute:[RKRoute
routeWithClass:[CompletedAssessment class]
pathPattern:#"clients/:response.clientId/responses"
method:RKRequestMethodPOST]] ;
Logging reveals the end JSON appears in this format:
{"response":
{"interpretation":null,"id":null,"score":null,"client_id":15,"local_time":"2015-8-6 13:8:34","time_taken":5,"assessment_short_name":null,"assessment_id":8,"created":null},
"answer":[
{"answer_value":"0","id":null,"answer_text":null,"answer_history":null,"time_taken":null,"response_id":null,"question_number":1},
{"answer_value":"1","id":null,"answer_text":null,"answer_history":null,"time_taken":null,"response_id":null,"question_number":2}
]}
And RestKit logging confirms the null mapping:
restkit.object_mapping:RKMappingOperation.m:873 Mapped relationship object from keyPath 'response' to 'response'. Value: {
"assessment_id" = 8;
"assessment_short_name" = "<null>";
"client_id" = 15;
created = "<null>";
id = "<null>";
interpretation = "<null>";
"local_time" = "2015-8-6 13:8:34";
score = "<null>";
"time_taken" = 5;
}
restkit.object_mapping:RKMappingOperation.m:715 Mapped attribute value from keyPath 'identifier' to 'id'. Value: (null)
...
Please help!
You are creating a new mapping calling [selfCompletedAssessmentMapping inverseMapping] in this line:
RKRequestDescriptor *requestDescriptor = [RKRequestDescriptor requestDescriptorWithMapping:[selfCompletedAssessmentMapping inverseMapping] objectClass:[CompletedAssessment class] rootKeyPath:nil method:RKRequestMethodPOST];
Save it to a variable and assign assignsDefaultValueForMissingAttributes to NO before creating the descriptor:
RKObjectMapping *requestMapping = [selfCompletedAssessmentMapping inverseMapping];
requestMapping.assignsDefaultValueForMissingAttributes = NO;
RKRequestDescriptor *requestDescriptor = [RKRequestDescriptor requestDescriptorWithMapping:requestMapping objectClass:[CompletedAssessment class] rootKeyPath:nil method:RKRequestMethodPOST];
Below is the JSON response that I get back:
{
"notificationId": 121,
"activities": [
143,
149]
}
Below is the mapping:
RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[NSMutableDictionary class]];
[mapping addAttributeMappingsFromDictionary:#{#"notificationId" : #"notificationId",
#"activities": #"activities"}];
RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:mapping
method:RKRequestMethodGET
pathPattern:nil
keyPath:#""
statusCodes:statusCodeSet];
[self.objectManager postObject:invitation path:#"/notifications" parameters:nil success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
NSString *notificationId1 = [mappingResult.dictionary valueForKey:#"notificationId"];
NSArray *activitesArray1 = [mappingResult.dictionary valueForKey:#"activities"];
NSString *notificationId2 = [mappingResult.dictionary objectForKey:#"notificationId"];
NSArray *activitesArray2 = [mappingResult.dictionary objectForKey:#"activities"];
NSLog(#"notificaiton ID %#", notificationId1);
NSLog(#"Activites %#", activitesArray1);
NSLog(#"notification ID %#", notificationId2);
NSLog(#"Activites %#", activitesArray2);
NSLog(#"Activites Array %#", activitesArray);
NSLog(#"mappingResult Dictionary %#", mappingResult.dictionary);
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
NSLog(#"Failusre");
}];
}
Log:
2014-04-21 19:17:51.273 App[57446:4403] I restkit.network:RKObjectRequestOperation.m:250 POST 'http://www.domain.com/notifications' (200 OK / 1 objects) [request=0.2371s mapping=0.0035s total=0.2446s]
2014-04-21 19:17:51.274 App[57446:60b] notification ID (null)
2014-04-21 19:17:51.274 App[57446:60b] Activites (null)
2014-04-21 19:17:51.274 App[57446:60b] notification ID (null)
2014-04-21 19:17:51.274 App[57446:60b] Activites (null)
2014-04-21 19:17:51.274 App[57446:60b] Activites Array (
)
2014-04-21 19:17:51.275 App[57446:60b] mappingResult Dictionary {
"" = {
activities = (
143,
149
);
notificationId = 121;
};
}
Why are all the values Null? How can I get the values of notificationId back as an NSString and activitiesin an array ? Can this be done without creating a mapping class?
Because your response descriptor is wrong. It should be:
[RKResponseDescriptor responseDescriptorWithMapping:mapping
method:RKRequestMethodPOST
pathPattern:#"/notifications"
keyPath:nil
statusCodes:statusCodeSet];
so that it matches the request you're sending (a POST, not a GET is the main issue).
For some unknow reason, it looks like, there is a wrapper object in the dictionary, that has key value #"" so first extract that and then everything else. Activities itself do look like array, so simply:
NSArray *activities = [[mappingResult.dictionary objectForKey:#""] objectForKey:#"activities"];
However that notification looks tricky, because it probably is a number. So if it is a consistent type, use:
NSNumber *notificationID = [[mappingResult.dictionary objectForKey:#""] objectForKey:#"notificationId"];
NSSring *notificationIDString = [notificationID stringValue];
So, i m sending a POST request for the first time. I m Mapping classes and as I thought and read from the Documentation that it would work in this way:
Init RK:
- (void)initRK{
if(!manager){
manager = [RKObjectManager managerWithBaseURL:[NSURL URLWithString:BASE_CONTEXT_URL]];
}
if (!reqMapping) {
reqMapping = [RKObjectMapping requestMapping];
}
}
POST Method:
// Configure a request mapping for our Article class. We want to send back title, body, and publicationDate
RKObjectMapping* deviceRequestMapping = [RKObjectMapping mappingForClass:[DeviceDTO class]];
[deviceRequestMapping addAttributeMappingsFromArray:#[ #"model", #"name", #"systemName", #"systemVersion", #"devToken" ]];
RKObjectMapping* msRequestMapping = [RKObjectMapping mappingForClass:[MemberShipDTO class]];
[msRequestMapping addAttributeMappingsFromArray:#[ #"validSince", #"validTill" ]];
RKObjectMapping* countryRequestMapping = [RKObjectMapping mappingForClass:[CountryDTO class]];
[countryRequestMapping addAttributeMappingsFromArray:#[ #"idNumberDTO", #"iso2DTO", #"short_nameDTO", #"calling_codeDTO" ]];
RKObjectMapping* userRequestMapping = [RKObjectMapping requestMapping];
[userRequestMapping addAttributeMappingsFromArray:#[ #"displayName", #"phoneNumber", #"status", #"userID" ]];
[userRequestMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:nil toKeyPath:#"device" withMapping:deviceRequestMapping]];
[userRequestMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:nil toKeyPath:#"memberShip" withMapping:msRequestMapping]];
[userRequestMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:nil toKeyPath:#"country" withMapping:countryRequestMapping]];
RKRequestDescriptor *requestDescriptor = [RKRequestDescriptor requestDescriptorWithMapping:userRequestMapping objectClass:[User class] rootKeyPath:#"user"];
//Create Objects
UserDTO *user = [[UserDTO alloc]init];
user.displayName = userDTO.displayName;
user.phoneNumber = userDTO.phoneNumber;
user.status = userDTO.status;
user.userID = userDTO.userID;
user.country = userDTO.country;
DeviceDTO *device = [[DeviceDTO alloc]init];
device.name = devDTO.name;
device.systemName = devDTO.systemName;
device.systemVersion = devDTO.systemVersion;
device.model = devDTO.model;
device.devToken = [[NSUserDefaults standardUserDefaults]objectForKey:PUSHTOKEN_USER_DEFAULTS_KEY];
user.deviceInfo = device;
MemberShipDTO *ms = [[MemberShipDTO alloc]init];
ms.validSince = [NSDate date];
ms.validTill = [[UtilitieHandler new] getDateByAdd:+1 :0 :0 :0];
user.memberShipDetails = ms;
[RKMIMETypeSerialization registerClass:[RKNSJSONSerialization class] forMIMEType:#"application/json"];
[[RKObjectManager sharedManager] setRequestSerializationMIMEType:RKMIMETypeJSON];
[[RKObjectManager sharedManager] setAcceptHeaderWithMIMEType:RKMIMETypeJSON];
[[RKObjectManager sharedManager] addRequestDescriptor:requestDescriptor];
[[RKObjectManager sharedManager] postObject:user path:#"user/integrate" parameters:nil success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult){
RKLogInfo(#"Load collection of Articles: %#", mappingResult.array);
}failure:^(RKObjectRequestOperation *operation, NSError *error) {
RKLogError(#"Operation failed with error: %#", error);
}];
So I tried different things and after i used wireshark to capture the request it returns that theres no content send. That means the mapping is not working correct. I tried a lot and nothing helped. Any advice would be great!
Here the captured packet:
POST /WAZZUUPWS/rest/service/user/integrate HTTP/1.1
Host: 192.168.2.115:8080
Accept-Encoding: gzip, deflate
Accept: application/json
Content-Length: 0
Connection: keep-alive
Accept-Language: de;q=1, en;q=0.9, fr;q=0.8, ja;q=0.7, nl;q=0.6, it;q=0.5
User-Agent: WAZZUUP!/1.0 (iPhone; iOS 6.1.4; Scale/2.00)
It might just be a typo in your question but requestDescriptor doesn't appear to be linked to the UserDTO class.
It seems like you do not have an understanding of Core Data objects yet. Objects that are persisted using Core Data are subclasses of NSManagedObject and have to be created differently. Read further on this link:
http://developer.apple.com/library/mac/#documentation/cocoa/conceptual/CoreData/Articles/cdCreateMOs.html
As for the current problem, you have to use this instead:
NSEntityDescription *entity = [NSEntityDescription entityForName:#"UserDTO" inManagedObjectContext:[RKManagedObjectStore defaultStore].mainQueueManagedObjectContext];
UserDTO *user = [[NSManagedObject alloc] initWithEntity:entity insertIntoManagedObjectContext:nil];
However, if UserDTO is a subclass of NSObject, that would need to change to NSManagedObject.
My workflow is something like this - create Core Data model and use mogenerator to automatically generate the NSManagedObject class definitions. Read more about it here:http://raptureinvenice.com/getting-started-with-mogenerator/
I have a JSON end path which accepts post requests in the following format.
{'values': [
{
"date":<measurement date as Unix time stamp>
"value":<weight>
}
{
"date":<measurement date as Unix time stamp>
"value":<weight>
}
...]}
"Values" is represented by the class "EntryCollection", while each value is represented by the class "Entry". I am puzzled finding the correct way to map my objects to the JSON representation. Right now I have the following code which causes the error: "The mapping operation was unable to find any nested object representations at the key paths searched".
RKObjectMapping *entryMapping = [RKObjectMapping requestMapping];
RKObjectMapping *valuesMapping = [RKObjectMapping mappingForClass:[EntriesCollection class]];
[valuesMapping addAttributeMappingsFromDictionary:[EntryCollection attributesMapping]];
[singleEntryMapping addAttributeMappingsFromDictionary:[SingleEntry attributesMapping]];
[singleEntryMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:#"entries" toKeyPath:#"entries" withMapping:valuesMapping]];
RKRequestDescriptor *requestDescriptor = [RKRequestDescriptor requestDescriptorWithMapping:entryMapping
objectClass:mappedClass
rootKeyPath:nil];
[self.objectManager addRequestDescriptor:requestDescriptor];
NSString *path = [self pathForPOST];
[self.objectManager postObject:weights path:path parameters:nil success:nil failure:nil];
EDIT for data structure
My data structure is simple (I suppose):
EntryCollection
- NSArray *entries (a collection of objects of type Entry)
Entry
- NSDate *date
- NSNumber *weight;
I would like to POST an EntryCollection filled with entries. The mapping of EntryCollection is "entries -> values", the one of Entry is "date -> date, weight -> value".
In any case, your JSON request payload must confirm to following data structure:
NSArray
|
|______NSDictionary ->Key: Date Value: weight
| ->Key: value Value: weight
|
|______NSDictionary ->Key: Date Value: weight
| ->Key: value Value: weight
|
|______NSDictionary ->Key: Date Value: weight
->Key: value Value: weight
Both NSArray and NSDictionary are fully compatible with JSON data format. I don't know about your underlying object structure, but ultimately this array should get posted as request payload NSData, and you will be done.
Well, if you have an issue in mapping, then you'll either have to show your model and class and mapping, or put RKLogConfigureByName("RestKit/ObjectMapping", RKLogLevelTrace); somewhere in your code and let us see output.
As an alternative, if your entities structure varies from what you want to Post to the server, you can use embedded AFNetworking client and do a simple request.
[[RKObjectManager sharedManager].HTTPClient postPath:#"" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"WHOOO");
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//
}];
I have found the solution. Turns out, I needed a relationship mapping to describe the hierarchy implied in the JSON. Since there is no type for each entity of values, I created an "empty" mapping and added the relationship mapping to it.
I also forgot to set the correct MIMEType and inverse the attributes mapping of my class. I guess a few days in restkit are needed to get a grasp of it.
RKObjectMapping *entryMapping = [RKObjectMapping requestMapping];
[entryMapping addAttributeMappingsFromDictionary:[SingleEntry attributesMapping]];
RKObjectMapping *entrySerializedMapping = [entryMapping inverseMapping];
RKRelationshipMapping *entryRelationship = [RKRelationshipMapping relationshipMappingFromKeyPath:#"entries" toKeyPath:#"values" withMapping:entrySerializedMapping];
RKObjectMapping *valueMapping = [RKObjectMapping requestMapping];
[valueMapping addPropertyMapping:valueMapping];
RKRequestDescriptor *descriptor = [RKRequestDescriptor requestDescriptorWithMapping:valueMapping objectClass:[EntriesCollection class] rootKeyPath:nil];
[self.objectManager addRequestDescriptor:descriptor];
self.objectManager.requestSerializationMIMEType = RKMIMETypeJSON;
NSString *path = [self pathForPOST];
[self.objectManager postObject:entryCollection path:path parameters:nil success:nil failure:nil];
I am trying to read data from server using RestKit 0.20 in my iOS app and getting the following error :
//Error
`… I restkit:RKLog.m:34 RestKit logging initialized...`
`… I restkit.support:RKMIMETypeSerialization.m:115 JSON Serialization class 'RKNSJSONSerialization' detected: Registering for MIME Type 'application/json`
`... T restkit.network:RKHTTPRequestOperation.m:139 GET '(null)':
request.headers={
Accept = "application/json";
"Accept-Language" = "en, fr, de, ja, nl, it, es, pt, pt-PT, da, fi, nb, sv, ko, zh-Hans, zh-Hant, ru, pl, tr, uk, ar, hr, cs, el, he, ro, sk, th, id, ms, en-GB, ca, hu, vi, en-us;q=0.8";
"User-Agent" = "XXXXX/1.0 (iPhone Simulator; iOS 5.0; Scale/1.00)";
}
request.body=(null)`
`... E restkit.network:RKHTTPRequestOperation.m:150 GET '(null)' (0):
error=Error Domain=NSURLErrorDomain Code=-1000 "bad URL" UserInfo=0x6c9d570 {NSUnderlyingError=0x6c9d460 "bad URL", NSLocalizedDescription=bad URL}
response.body=(null)`
`... E restkit.network:RKObjectRequestOperation.m:270 Object request failed: Underlying HTTP request operation failed with error: Error Domain=NSURLErrorDomain Code=-1000 "bad URL" UserInfo=0x6c9d570 {NSUnderlyingError=0x6c9d460 "bad URL", NSLocalizedDescription=bad URL}`
`... Hit error: Error Domain=NSURLErrorDomain Code=-1000 "bad URL" UserInfo=0x6c9d570 {NSUnderlyingError=0x6c9d460 "bad URL", NSLocalizedDescription=bad URL}`
Here is the JSON received from server:
[ {
"array1" : [ {
"a1prop1" : 1,
"a1prop2" : "prop21val",
}, {
"a1prop1" : 2,
"a1prop2" : "prop22val",
}, {
"a1prop1" : 3,
"a1prop2" : "prop23val",
} ],
"property1" : prop1val,
"property2" : "prop2val",
"property3" : "prop3val",
} ]
Mappings using RestKit:
-(void) getData {
………………...
NSURL *baseURL = [NSURL URLWithString:stringURL];
AFHTTPClient* client = [[AFHTTPClient alloc] initWithBaseURL:baseURL];
[client setDefaultHeader:#"Accept" value:RKMIMETypeJSON];
RKObjectManager *objectManager = [[RKObjectManager alloc] initWithHTTPClient:client];
[objectManager setAcceptHeaderWithMIMEType:RKMIMETypeJSON];
RKObjectMapping *array1Mapping = [RKObjectMapping mappingForClass:[ArrayOneClass class]];
[array1Mapping addAttributeMappingsFromDictionary:#{
#"a1Prop1" : #"a1Prop1",
#"a1Prop2" : #"a1Prop2",
}];
RKObjectMapping *mainObjectMapping = [RKObjectMapping mappingForClass:[MainObjectClass class]]
[mainObjectMapping addAttributeMappingsFromDictionary:#{
#"property1" : #"property1",
#"property2" : #"property2",
#"property3" : #"property3",
}];
RKRelationshipMapping *mainObjRelationMapping = [RKRelationshipMapping relationshipMappingFromKeyPath:#"array1" toKeyPath:#"array1" withMapping:array1Mapping];
[mainObjectMapping addRelationshipMappingWithSourceKeyPath:#"array1" mapping: mainObjRelationMapping.mapping];
RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:mainObjectMapping pathPattern:nil
keyPath:nil
statusCodes:[NSIndexSet indexSetWithIndex:200]];
[objectManager addResponseDescriptor:responseDescriptor];
NSString *pathStr = [NSString stringWithFormat:#"/api/getAllObjects"];
[objectManager getObjectsAtPath:pathStr
parameters:nil
success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
NSLog(#"...success");
}
failure:^(RKObjectRequestOperation *operation, NSError *error) {
NSLog(#"Hit error: %#", error);
}];
}
MainObject Class:
//MainObjectClass.h
#interface MainObjectClass : NSObject{
int property1;
NSString * property2;
NSString * property3;
NSSet *array1;
}
#property (nonatomic) int property1;
#property (nonatomic, retain) NSString * property2;
#property (nonatomic, retain) NSString * property3;
#property (nonatomic, retain) NSSet *array1;
- (NSDictionary*)elementToPropertyMappings;
- (NSDictionary*)elementToRelationshipMappings;
#end
//MainObjectClass.m
#implementation MainObjectClass
#synthesize property1, property2, property3, array1;
- (NSDictionary*)elementToPropertyMappings {
return [NSDictionary dictionaryWithObjectsAndKeys:
#"property1", #"property1",
#"property2", #"property2",
#"property3", #"property3",
nil];
}
- (NSDictionary *)elementToRelationshipMappings {
return [NSDictionary dictionaryWithObjectsAndKeys:
#"array1", #"array1",
nil];
}
#end
Can anyone please tell me why this is not generating proper request? It is not hitting the server at all. I tried simple get/post methods with no relationship mappings and they all are working fine with RestKit mappings. Appreciate your views. Thanks.
try this :- use property of RKObjectManager
objectManager.serializationMIMEType = RKMIMETypeJSON;