I'm trying to map objects through RestKit 0.20.3, but I'm having those logs for days know:
2013-08-12 18:32:08.158 MyAppIphone[848:5703] E restkit.network:RKResponseMapperOperation.m:304 Failed to parse response data: Loaded an unprocessable response (200) with content type 'application/json'
2013-08-12 18:32:08.174 MyAppIphone[848:5703] E restkit.network:RKObjectRequestOperation.m:238 POST 'myUrl' (200 OK / 0 objects)
[request=0.1305s mapping=0.0000s total=5.6390s]:
error=Error Domain=org.restkit.RestKit.ErrorDomain Code=-1017 "Loaded an unprocessable response (200) with content type 'application/json'"
UserInfo=0x1ed5a500 {NSErrorFailingURLKey=myUrl, NSUnderlyingError=0x1ed5b240 "The operation couldn’t be completed. (Cocoa error 3840.)", NSLocalizedDescription=Loaded an unprocessable response (200) with content type 'application/json'}
response.body={"my json content"}
Here is MyData class:
#import <Foundation/Foundation.h>
#interface MyData : NSObject
#property (nonatomic, retain) NSString *criterias;
#end
Here is how I set up my mapper:
- (RKResponseDescriptor*) getDataMapping
{
// Mapping
RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[MyData class]];
[mapping addAttributeMappingsFromDictionary:#{
#"criteriasHeader": #"criteriasHeader"
}];
// Status code
NSIndexSet *statusCodes = RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful);
// Descriptior
return [RKResponseDescriptor responseDescriptorWithMapping:mapping method:RKRequestMethodPOST pathPattern:nil keyPath:#"regions" statusCodes:statusCodes];
}
Here my requesting function:
- (void) runRequestWithType:(RequestType)type baseUrl:(NSString *)baseUrlString path:(NSString *)path parameters:(NSDictionary *)parameters mapping:(RKResponseDescriptor *) descriptor
{
// Print heeader and body from the request and the response
RKLogConfigureByName("RestKit/Network", RKLogLevelTrace);
RKLogConfigureByName("Restkit/Network", RKLogLevelDebug);
RKLogConfigureByName("RestKit/ObjectMapping", RKLogLevelTrace);
RKLogConfigureByName("Restkit/ObjectMapping", RKLogLevelDebug);
// Set up the base url
NSURL *baseUrl = [NSURL URLWithString:baseUrlString];
//Run request in block
RKObjectManager *manager = [RKObjectManager managerWithBaseURL:baseUrl];
[manager addResponseDescriptorsFromArray:#[descriptor]];
[manager.router.routeSet addRoute:[RKRoute routeWithClass:[MyData class] pathPattern:path method:RKRequestMethodPOST]];
//[manager getObjectsAtPath:path parameters:parameters success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
[manager postObject:nil path:path parameters:parameters success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
if ([self.delegate respondsToSelector:#selector(requestDidSucceedWithType:andResponse:)]) {
[self.delegate requestDidSucceedWithType:type andResponse:[mappingResult firstObject]];
}
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
if ([self.delegate respondsToSelector:#selector(requestDidFailWithError:andError:)]) {
[self.delegate requestDidFailWithType:type andError:error];
}
}];
}
PS: I tried with a shorter JSON, it works well.
Did I do something wrong?
Could you help me, thanks.
This kind of error comes from JSON mapping under RK. Default is to use NSJSONSerialization encapsulated in RKNSJSONSerialization. You can put a breakpoint there to find out maybe more about the error.
I found 2 sources until now:
NSJSONSerialization doesn't like non UTF8 data. Make sure you either receive it from server, or modify RK to do the proper conversion from data to string(with correct encoding) to UTF8-data(best way i have so far). If using CoreData you can look in RKManagedObjectRequestOperation at line 586.
in iOS5 there are bugs. Easiest fix is to use another parsing library
Hopefully you are able to change the server encoding of the JSON to UTF-8.
If not, you can resolve this issue by replacing the default JSON mime type handler in Restkit. Use the Restkit class RKNSJSONSerialization as reference.
In your custom JSON mime type handler, perform data conversion from the incoming encoding (in the example below ISO-8859-1) to UTF-8, before doing the same as the RKNSJSONSerialization class.
#implementation MyCustomJSONSerializer
+ (id)objectFromData:(NSData *)data error:(NSError **)error
{
NSString* latin = [[NSString alloc] initWithBytes:[data bytes] length:[data length] encoding:NSISOLatin1StringEncoding];
NSData* utf8 = [latin dataUsingEncoding:NSUTF8StringEncoding];
return [NSJSONSerialization JSONObjectWithData:utf8 options:0 error:error];
}
#end
You can do similar for the dataFromObject method if you must POST data back to the server in non-UTF-8 encoding.
You can now add this custom handler after you init Restkit, and it will be used vs the default (UTF-8) one:
[RKMIMETypeSerialization registerClass:[MyCustomJSONSerializer class] forMIMEType:RKMIMETypeJSON];
Related
I am learning Rest-kit. i am trying to parse this url https://api.coursera.org/api/catalog.v1/courses?fields=language,shortDescription
I have created one Courses class.
#interface Courses : NSObject
#property (nonatomic, strong) NSString *name;
#end
and in viewcontroller i have wrote below code
- (void)viewDidLoad
{
[super viewDidLoad];
[self configureRestKit];
[self loadCourses];
}
- (void)configureRestKit
{
// https://api.coursera.org/api/catalog.v1/courses?fields=language,shortDescription
// initialize AFNetworking HTTPClient
NSURL *baseURL = [NSURL URLWithString:#"https://api.coursera.org"];
AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:baseURL];
// initialize RestKit
RKObjectManager *objectManager = [[RKObjectManager alloc] initWithHTTPClient:client];
// setup object mappings
RKObjectMapping *courseMapping = [RKObjectMapping mappingForClass:[Courses class]];
[courseMapping addAttributeMappingsFromDictionary:#{
#"name":#"name"
}];
// register mappings with the provider using a response descriptor
RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:courseMapping method:RKRequestMethodGET pathPattern:#"/api/catalog.v1/courses?fields=language,shortDescription" keyPath:#"elements" statusCodes:[NSIndexSet indexSetWithIndex:200]];
[objectManager addResponseDescriptor:responseDescriptor];
}
- (void)loadCourses
{
[[RKObjectManager sharedManager] getObjectsAtPath:#"/api/catalog.v1/courses?fields=language,shortDescription" parameters:nil success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
NSLog(#"%#", mappingResult.array);
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
NSLog(#"What do you mean by 'there is no Courses?': %#", error);
}];
}
ERROR :_Error Domain=org.restkit.RestKit.ErrorDomain Code=1001 "No response descriptors match the response loaded."
I am not getting response in success block. Please correct me. Thanks in advance
Don't add your query parameters to the path pattern on the response descriptor, and set them as parameters on the request:
pathPattern:#"/api/catalog.v1/courses"
generally I would also say that /api/catalog.v1/ should be part of the base URL so you would have:
NSURL *baseURL = [NSURL URLWithString:#"https://api.coursera.org/api/catalog.v1/"];
...
... pathPattern:#"courses" ...
...
... getObjectsAtPath:#"courses" parameters:#{ #"fields" : #"language,shortDescription" } ...
I'm using restkit on IOS. I'm having trouble parsing a simple json object.
I have a simple json object returned:
{"_id"=>"537c235189d50fabcc000009",
"about"=>"nice",
"headline"=>"looking",
"access_token"=>
"$2a$10$oZ4IiaVBxHhc1qGeBoZv1uYonBM3Qb5Y010rTkUOynDZIGdGagqJy"}
My setup:
- (void)viewDidLoad
{
[super viewDidLoad];
[self configureRestKit];
[self loadVenues];
}
- (void)loadVenues
{
NSString *clientToken = SNAPTOKEN;
NSDictionary *profile = #{#"os": #"iOS",
#"device_token": #"first_token",
#"password":#"password",
#"email":#"email",
#"headline":#"hello world"};
NSDictionary *queryParams = #{#"token" : clientToken,
#"profile" : profile};
[[RKObjectManager sharedManager] postObject: nil
path: #"/profiles/new"
parameters:queryParams
success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
NSLog(#"log%#", mappingResult );
_profile = mappingResult.array;
}
failure:^(RKObjectRequestOperation *operation, NSError *error) {
NSLog(#"What do you mean by 'there is no coffee?': %#", error);
}];
}
- (void)configureRestKit
{
// initialize AFNetworking HTTPClient
NSURL *baseURL = [NSURL URLWithString:#"https://airimg.com"];
AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:baseURL];
// initialize RestKit
RKObjectManager *objectManager = [[RKObjectManager alloc] initWithHTTPClient:client];
// setup object mappings
RKObjectMapping *venueMapping = [RKObjectMapping mappingForClass:[Profile class]];
[venueMapping addAttributeMappingsFromDictionary:#{ #"_id": #"about", #"access_token": #"headline" }];
// register mappings with the provider using a response descriptor
RKResponseDescriptor *responseDescriptor =
[RKResponseDescriptor responseDescriptorWithMapping:venueMapping
method:RKRequestMethodPOST
pathPattern:#"/profiles/new"
keyPath:#"response"
statusCodes:[NSIndexSet indexSetWithIndex:200]];
[objectManager addResponseDescriptor:responseDescriptor];
}
I have the following error:
NSLocalizedFailureReason=The mapping operation was unable to find any nested object representations at the key paths searched: response
The representation inputted to the mapper was found to contain nested object representations at the following key paths: _id, about, access_token, headline
This likely indicates that you have misconfigured the key paths for your mappings., NSLocalizedDescription=No mappable object representations were found at the key paths searched., keyPath=null}
The main problem is that your response descriptor uses a key path of response and your JSON doesn't include that key at the top level. So, set the key path to 'nil'.
Also, your view controller should store the reference to the objectManager and use it again later. Currently you use [RKObjectManager sharedManager] and that returns the first object manager that was ever created so as soon as you have multiple view controllers each creating their own object manager you will have issues.
Of course, the view controllers shouldn't necessarily be creating individual object managers...
I want to get this JSON data with my iOS app: https://sleepy-journey-2871.herokuapp.com/users.json .... RestKit tries to get these users from the url, but it returns 0 objects and says "No mappable representations were found at the key paths searched. No response descriptors match the response loaded."
PLEASE help me figure out what I'm missing or doing wrong! I've been battling this for weeks.
I have Xcode 5.0.2, I successfully installed RestKit with Cocoapods and a Podfile that looks like this:
platform :ios, '6.0'
pod 'RestKit', '~> 0.22.0'
pod 'RestKit/Testing'
pod 'RestKit/Search'
My AppDelegate.m file is below (the didFinishLaunchingWithOptions method):
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
//Set base url
NSString *baseUrl = #"https://sleepy-journey-2871.herokuapp.com";
//initialize the the http client with baseUrl
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:baseUrl]];
//initialize the RKObjectManager with our http client
RKObjectManager *manager = [[RKObjectManager alloc] initWithHTTPClient:httpClient];
//add text/plain as a JSON content type to properly parse errors
[RKMIMETypeSerialization registerClass:[RKNSJSONSerialization class] forMIMEType:#"text/plain"];
//register JSONRequestOperation to parse JSON in requests
[manager.HTTPClient registerHTTPOperationClass:[AFJSONRequestOperation class]];
//state that we are accepting JSON content type
[manager setAcceptHeaderWithMIMEType:RKMIMETypeJSON];
//configure so that we want the outgoing objects to be serialized into JSON
manager.requestSerializationMIMEType = RKMIMETypeJSON;
//set the shared instance of the object manager, so that we can easily re-use it later
[RKObjectManager setSharedManager:manager];
return YES;
}
I have this code in the viewDidLoad method of the view controller that first loads when the app is launched:
- (void)viewDidLoad
{
[super viewDidLoad];
RKObjectManager *manager = [RKObjectManager sharedManager];
[manager getObjectsAtPath:#"/users"
parameters:nil
success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult)
{
NSLog(#"Loaded databases: %#", [mappingResult array]);
}
failure:^(RKObjectRequestOperation *operation, NSError *error)
{
NSLog(#"Error: %#", [error localizedDescription]);
}];
// Do any additional setup after loading the view, typically from a nib.
}
You have to:
Create a User class.
Create a mapping for User class.
Create a response descriptor.
Pseudocode could look something like:
#interface User : NSObject
#property (nonatomic, copy) NSNumber *userID;
#property (nonatomic, copy) NSString *name;
...
#end
RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[User class]];
[mapping addAttributeMappingsFromDictionary:#{
#"name": #"name",
#"id": #"userID"
...
}];
RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:mapping
method:RKRequestMethodAny
pathPattern:nil
keyPath:nil
statusCodes:nil];
...
RKObjectRequestOperation *operation = [[RKObjectRequestOperation alloc] initWithRequest:request
responseDescriptors:#[responseDescriptor]];
[operation setCompletionBlockWithSuccess:^(RKObjectRequestOperation *operation, RKMappingResult *result) {
NSLog(#"The public timeline Tweets: %#", [result array]);
} failure:nil];
[operation start];
Take a look at examples here.
I have tried several StackOverflow questions, and I caanot find the correct answer on this. I am using the POSTMAN plugin for Chrome to check my REST calls and I cannot figure out why I cannot read the response. In the comments you will see all the different attempts I have made to get the response.
NSDictionary* session_params = #{SESSION_USERNAME_KEY:SESSION_USERNAME_VALUE, SESSION_PASSWORD_KEY:SESSION_PASSWORD_VALUE};
NSURL* url = [NSURL URLWithString:SESSION_URL];
RKObjectManager* objectManager = [RKObjectManager managerWithBaseURL:url];
//GET THE **** THING TO INTERPRET A TEXT response
//[RKMIMETypeSerialization registerClass:[RKXMLReaderSerialization class] forMIMEType:RKMIMETypeTextXML];
//[objectManager setAcceptHeaderWithMIMEType:#"text/html"];
//[objectManager setAcceptHeaderWithMIMEType:RKMIMETypeTextXML];
//[RKMIMETypeSerialization registerClass:[RKXMLReaderSerialization class] forMIMEType:#"text/html"];
//[RKMIMETypeSerialization registerClass:[RKNSJSONSerialization class] forMIMEType:#"text/html"];
//[objectManager setRequestSerializationMIMEType:#"text/html"];
//END
NSMutableURLRequest* request = [objectManager requestWithObject:nil method:RKRequestMethodPOST path:SESSION_URL parameters:session_params];
RKObjectRequestOperation* operation = [objectManager
objectRequestOperationWithRequest:request success:^(RKObjectRequestOperation* operation, RKMappingResult* result)
{
NSLog(#"RESULT [%#]", result);
}
failure:^(RKObjectRequestOperation *operation, NSError *error) {
NSLog(#"ERROR [%#]", error);
}];
[operation start];
I think the most irritating thing is that the stuff I need is contained in the NSLocalizedRecoverySuggestion value. It is a session key I require.
OUTPUT:
E restkit.network:RKObjectRequestOperation.m:547 Object request failed: Underlying HTTP request operation failed with error: Error Domain=org.restkit.RestKit.ErrorDomain Code=-1016 "Expected content type {(
"application/x-www-form-urlencoded",
"application/json"
)}, got text/html" UserInfo=0x1c52aed0 {NSLocalizedRecoverySuggestion=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJCbG8uUmVnQWxlcnQuQnJva2VyIiwiYXVkIjoiaHR0cDovL2xvY2FsaG9zdC9CbG8uUmVnQWxlcnQuQVBJL2FwaSIsIm5iZiI6MTM5MjY0MTY2MSwiZXhwIjoxMzkyNjQ1MjYxLCJ1bmlxdWVfbmFtZSI6IkJ1dHRvbnMiLCJyb2xlIjoiUmVnQWxlcnRDb25zdW1lciJ9.JCTMGJRKlOxEtNrcGodpce-tqsRS4zlApNisKQW6iSw, AFNetworkingOperationFailingURLRequestErrorKey=, NSErrorFailingURLKey=http://..., NSLocalizedDescription=Expected content type {(
"application/x-www-form-urlencoded",
"application/json"
)}, got text/html, AFNetworkingOperationFailingURLResponseErrorKey=}
2014-02-17 14:54:20.808 AppName[5600:6403] E restkit.network:RKObjectRequestOperation.m:213 POST 'http://...' (200 OK / 0 objects) [request=0.0000s mapping=0.0000s total=0.1925s]: Error Domain=org.restkit.RestKit.ErrorDomain Code=-1016 "Expected content type {(
"application/x-www-form-urlencoded",
"application/json"
)}, got text/html" UserInfo=0x1c52aed0 {NSLocalizedRecoverySuggestion=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJCbG8uUmVnQWxlcnQuQnJva2VyIiwiYXVkIjoiaHR0cDovL2xvY2FsaG9zdC9CbG8uUmVnQWxlcnQuQVBJL2FwaSIsIm5iZiI6MTM5MjY0MTY2MSwiZXhwIjoxMzkyNjQ1MjYxLCJ1bmlxdWVfbmFtZSI6IkJ1dHRvbnMiLCJyb2xlIjoiUmVnQWxlcnRDb25zdW1lciJ9.JCTMGJRKlOxEtNrcGodpce-tqsRS4zlApNisKQW6iSw, AFNetworkingOperationFailingURLRequestErrorKey=, NSErrorFailingURLKey=http://..., NSLocalizedDescription=Expected content type {(
"application/x-www-form-urlencoded",
"application/json"
)}, got text/html, AFNetworkingOperationFailingURLResponseErrorKey=}
CODE THAT WORKED
Thanks to Wain for pointing me on the correct path there. I am a little disappointed that RestKit cannot handle such a simple request, and I need RestKit because this is just a session token to calling the other methods, but whatever works I guess:
NSDictionary* session_params = #{SESSION_USERNAME_KEY:SESSION_USERNAME_VALUE, SESSION_PASSWORD_KEY:SESSION_PASSWORD_VALUE};
NSURL* url = [NSURL URLWithString:SESSION_URL];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
NSMutableURLRequest *request = [httpClient requestWithMethod:#"POST" path:SESSION_URL parameters:session_params];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString* response = [operation responseString];
NSLog(#"response: %#",response);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"error: %#", [operation error]);
}];
[operation start];
This bit:
"Expected content type {( "application/x-www-form-urlencoded", "application/json" )}, got text/html"
tells you that you have told RestKit to expect form-urlencoded or json, but that the server is returning html.
You would probably want to use setAcceptHeaderWithMIMEType with JSON mime type to tell the server what you want back. But, in this case you probably just shouldn't be using RestKit.
RestKit is for mapping arbitrary JSON / XML data into your data model. You just have a key coming back. No mapping is required. So, don't use RestKit, use AFNetworking instead (which you have full access to because RestKit uses it internally.
Thanks to Wain and Quintin, this was quite useful to me :)
I think some names changed in more recent versions of Restkit or AFNetworking. I used AFNetworking as explained in other answers since the server did not return json but empty plain/text instead. This was only on a particular endpoint where I was looking for a token in the headers of the response.
Sharing my piece of code here too:
-(void) find_some_token_with_success:(void (^)(AFRKHTTPRequestOperation *operation, id responseObject))success failure:(void (^)(AFRKHTTPRequestOperation *operation, NSError *error))failure {
NSURL *baseURL = [NSURL URLWithString:#"https://example.com"];
AFRKHTTPClient *client = [AFRKHTTPClient clientWithBaseURL:baseURL];
[client setDefaultHeader:#"Accept" value:RKMIMETypeJSON];
[client setDefaultHeader:#"some_custom_header" value:#"some_custom_value"];
NSMutableURLRequest *request = [client requestWithMethod:#"GET" path:#"/api/v1/some_non_json_endpoint" parameters:nil];
AFRKHTTPRequestOperation *operation = [[AFRKHTTPRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:success failure:failure];
[operation start];
}
Then I used something like this to get the header I was looking for:
-(void) get_the_token:(void (^)(NSString *token))withTokenCallback failure:(void (^)(AFRKHTTPRequestOperation *operation, NSError *error))failure {
[self xsrftoken_with_success:^(AFRKHTTPRequestOperation *operation, id responseObject) {
NSString *token = [self get_the_token_from_response:[operation response]];
withTokenCallback(token);
} failure:failure];
}
-(NSString *) get_the_token_from_response: (NSHTTPURLResponse *) response;
{
NSDictionary *headerDictionary = response.allHeaderFields;
NSString *token = [headerDictionary objectForKey:#"SOME-TOKEN-KEY"];
return token;
}
So all of this can simply be used like this:
- (void)testGetSometokenInARequest
{
XCTestExpectation *expectation = [self expectationWithDescription:#"Query timed out."];
[[SomeRequestWithoutJsonResponse alloc]
get_the_token:^(NSString *token) {
[expectation fulfill];
NSLog(#"token: %#", token);
// this token should be 100 characters long
XCTAssertTrue([token length] == 100);
}
failure:^(AFRKHTTPRequestOperation *operation, NSError *error) {
NSLog(#"error: %#", [operation error]);
}];
[self waitForExpectationsWithTimeout:10.0 handler:nil];
}
In other words, get_the_token takes a callback with the desired token and a failure callback.
Make sure you still include <RestKit/RestKit> so you have access to Restkit's AFNetowkring :)
Alternative working solution using restkit:
RestKit: How to handle empty response.body?
And you register a serializer for that kind of Mimetype like this:
[RKMIMETypeSerialization registerClass:[RKNSJSONSerialization class] forMIMEType:#"text/plain"];
i am able to send request correctly but after receiving response i get
response.body ={"status":"success","loginToken":"xxxxyyyzzz"}
but with an error saying
It Failed: Error Domain=org.restkit.RestKit.ErrorDomain Code=1001 "No response descriptors
match the response loaded." UserInfo=0x2b55b0 {NSErrorFailingURLStringKey=http://192.168.1.71
/firstyii/index.php?r=site/login, NSLocalizedFailureReason=A 200 response was loaded from the
URL 'http://192.168.1.71/firstyii/index.php?r=site/login', which failed to match all (1)
response descriptors:
<RKResponseDescriptor: 0x2a5860 baseURL=http://192.168.1.71 pathPattern=/firstyii
/index.php?r=site/login statusCodes=200-299> failed to match: response path '/firstyii
/index.php?r=site/login' did not match the path pattern '/firstyii/index.php?r=site/login'.,
NSLocalizedDescription=No response descriptors match the response loaded., keyPath=null,
NSErrorFailingURLKey=http://192.168.1.71/firstyii/index.php?r=site/login,
NSUnderlyingError=0x2b6070 "No mappable object representations were found at the key paths
searched."}
LoginResponse.h
#interface LoginResponse : NSObject
#property (nonatomic, strong) NSString *status;
#property (nonatomic, strong) NSString *loginToken;
+(RKObjectMapping*)defineLoginResponseMapping;
#end
LoginResponse.m
#import "LoginResponse.h"
#implementation LoginResponse
#synthesize loginToken;
#synthesize status;
+(RKObjectMapping*)defineLoginResponseMapping {
RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[LoginResponse class]];
[mapping addAttributeMappingsFromDictionary:#{
#"status": #"status",
#"loginToken": #"loginToken",
}];
return mapping;
}
#end
Code in LoginManager.m
-(void)LoginWithUserName:(NSString *)username password:(NSString*)password {
LoginRequest *dataObject = [[LoginRequest alloc] init];
[dataObject setUsername:username];
[dataObject setPassword:password];
NSURL *baseURL = [NSURL URLWithString:#"http://192.168.1.71"];
AFHTTPClient * client = [AFHTTPClient clientWithBaseURL:baseURL];
[client setDefaultHeader:#"Accept" value:RKMIMETypeJSON];
RKObjectManager *objectManager = [[RKObjectManager alloc] initWithHTTPClient:client];
[RKMIMETypeSerialization registerClass:[RKNSJSONSerialization class]
forMIMEType:#"application/json"];
RKObjectMapping *requestMapping = [[LoginRequest defineLoginRequestMapping] inverseMapping];
[objectManager addRequestDescriptor: [RKRequestDescriptor
requestDescriptorWithMapping:requestMapping objectClass:[LoginRequest class] rootKeyPath:nil
]];
// what to print
RKLogConfigureByName("RestKit/Network", RKLogLevelTrace);
RKLogConfigureByName("Restkit/Network", RKLogLevelDebug);
RKObjectMapping *responseMapping = [LoginResponse defineLoginResponseMapping];
[objectManager addResponseDescriptor:[RKResponseDescriptor
responseDescriptorWithMapping:responseMapping pathPattern:#"/firstyii/index.php?r=site/login"
keyPath:nil statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)]];
[objectManager setRequestSerializationMIMEType: RKMIMETypeJSON];
[objectManager postObject:dataObject path:#"/firstyii/index.php?r=site/login"
parameters:nil success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
NSLog(#"It Worked: %#", [mappingResult array]);
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
NSLog(#"It Failed: %#", error);
}];
}
i think that the code used above is to map response with array ,
so i need code to map simple json like this one response.body={"status":"success","loginToken":"logingngngnnggngngae"}
Such responses are to be mapped using pathpattern , non keyvalue mapping mentioned at https://github.com/RestKit/RestKit/wiki/Object-mapping.
I was using pathPattern having "?" in it , hence it was not matching properly.
,also path pattern shouldnot have "/" at beginning.
the above code works fine if i change the pathPattern to pathPattern:#"site/login"
,and postObject to postObject:#"site/login"
and ofcourse changed the baseurl = #"http://json.xxxxxxx.xxxxx:8179/jsonresponse/index.php" so that there are not special charaters in it.