I have a 'JSON' data with different status codes, as shown in the image, I'm using 'AFHTTPSessionManager', And if we call the API I get 200 as success code, Apart from that in my response object I have status codes So I want to do different operations based on the status codes, For this I have written code like this..
-(void)validateOTP:(NSString *)OTP andUserID:(NSString *)userID withCompletion:(void(^)(NSDictionary* dictionary, NSError* error))completion
{
UTValidateOTPRequest *request = [UTValidateOTPRequest validateOTPRequestWithOTP:OTP andUserID:userID];
NSDictionary *paramDict = [request dictionaryRepresentation];
NSURLSessionDataTask *task = [self postRequestToResouce:[NSString stringWithFormat:#"%#/ValidateOTP",kServerCommonEndPoint] arguments:paramDict successHandler:^(NSDictionary *response) {
NSNumber *statusCode = response[kStatusCodeKey];
if (statusCode.integerValue == UTStatusCodeSuccess) {
completion(response, nil);
}
else {
NSError *error = [NSError mapStatusCodeToError:statusCode.integerValue details:response];
completion(nil, error);
}
} errorHandler:^(NSError *error) {
NSError *newError = [NSError mapStatusCodeToError:error.code details:error.userInfo];
completion(nil, newError);
}];
[self addDataTask:task];
}
As you can see, even inside success handler I'm passing error and calling a category method we have created.
NSError *error = [NSError mapStatusCodeToError:statusCode.integerValue details:response];
This method implemented as follows
+ (NSError *)mapStatusCodeToError: (NSInteger)statusCode details:(NSDictionary*) errorInfo
{
NSString *bundleIdentifier = [[NSBundle mainBundle] bundleIdentifier];
NSString *domain = [bundleIdentifier stringByAppendingString:kErrorDomainKey];
NSString *errorMessage = nil;
if (errorInfo[kErrorMessageKey] && ![errorInfo[kErrorMessageKey] isEqualToString:kEmptyString]) {
errorMessage = errorInfo[kErrorMessageKey];
}
else{
// use common message
errorMessage = kInternetNotAvailableMessage;
}
NSDictionary *userInfo = #{NSLocalizedDescriptionKey:NSLocalizedString(errorMessage, nil)};
NSLog(#"User INFO : %#",userInfo);
NSError *internetUnavailableError = [NSError errorWithDomain:domain
code:NSURLErrorNotConnectedToInternet
userInfo:userInfo];
NSLog(#"Error Code : %ld",(long)internetUnavailableError.code);
return internetUnavailableError;
}
Here I want to use the statusCode that I'm passing as parameter to this method so that I can get that status code where I'm calling this method
[[UTServerManager sharedInstance] validateOTP:self.enterOTPText.text andUserID:self.userId withCompletion:^(NSDictionary *dictionary, NSError *error) {
// Here I want to get the status code of error not like -1009 , but what ever statusCode that I'm getting from the API response.
}];
So in this method can I get the response status code if it is not success code means as you see in the image in the first response is success and remaining are error responses.
And I know that I can use the statusCode in the category method but I dont know how to use it, If I store this status-Code in the category method for error as above , that I'm passing as a parameter to the methods then I can call them where ever I require How to get this ?
And my restriction is I should these methods only but I have to add the response status code to error ??
Looks like you are passing a userInfo dict to the NSError. You could add to this dictionary prior to creating the NSError you are returning, and then later it would be available in the NSError callback.
Related
I had created the new project which fetches the track of songs, so I tried to pass an array of SPTTracks to the player, please find it below.
self.player = [[SPTAudioStreamingController alloc] initWithClientId:auth.clientID];
self.player.diskCache = [[SPTDiskCache alloc] initWithCapacity:1024 * 1024 * 64];
NSString *trackURI = #"spotify:track:1zHlj4dQ8ZAtrayhuDDmkY";
[SPTTrack trackWithURI:[NSURL URLWithString:trackURI] accessToken:auth.session.accessToken market:#"ES" callback:^(NSError *error, id object) {
if (!error) {
SPTTrack *trackInfo = object;
NSArray *tracks = #[trackInfo];
[self.player playURIs:tracks fromIndex:0 callback:^(NSError *error) {
if (!error) {
} else {
NSLog(#"*** Failed to play track : %#", error);
}
}];
} else {
NSLog(#"Error %#", error);
}
}];
But I get crashes, whenever I run it. Please find error below while it is getting crash :
Simple Track Playback[254:24669] -[__NSCFConstantString absoluteString]: unrecognized selector sent to instance 0x1000c0508
I had also looked it on spotify api spotify_ios_sdk but I had found that one developer had already posted the same issue link.
If anyone has solved these type of issue then please provide your guidance.
Thanks in advanced.
Unfortunately, this method is not "equivalent", because the SPTTrack object returned inside the callback of [SPTTrack trackWithURI.... has many less informations.
I've tried some workaround, and I found that for me the solution is
1) Create a request for an SPTTrack object.
2) Pass that request to SPRequest performRequest callback.
3) Wait for the response, and eventually create a track from data (please find the below complete code).
self.player = [[SPTAudioStreamingController alloc] initWithClientId:auth.clientID];
self.player.diskCache = [[SPTDiskCache alloc] initWithCapacity:1024 * 1024 * 64];
NSString *market = [[NSLocale currentLocale] objectForKey:NSLocaleCountryCode];
NSURLRequest *request = [SPTTrack createRequestForTrack:[NSURL URLWithString:#"spotify:track:1zHlj4dQ8ZAtrayhuDDmkY"]
withAccessToken:auth.session.accessToken
market:market
error:nil];
[[SPTRequest sharedHandler] performRequest:request
callback:^(NSError *error, NSURLResponse *response, NSData *data) {
if (!error) {
NSError *parsingError = nil;
SPTTrack *track = [SPTTrack trackFromData:data
withResponse:response
error:&parsingError];
self.arrURIs = #[track.playableUri];
[self.player playURIs:self.arrURIs fromIndex:0 callback:nil];
}
}];
Thanks "Kry256" for detail explaination.
Can i get variable value from block?
- (Params *) getParams {
__block Params* params = nil;
//make post, get requests
[JSONHTTPClient getJSONFromURLWithString:#"http://www.blankspot.ru/api/getinterval"
params:nil
completion:^(id json, JSONModelError *err) {
NSLog(#"json = %#", json);
NSLog(#"Error = %#", err );
NSDictionary* json1 = json;
NSLog(#" %# ob ", [json1 objectForKey:#"success"]);
params = [[Params alloc] initWithDictionary:json1 error:&err];
NSLog(#"params123 = %#", params); // is not null
}];
NSLog(#"params123 = %#", params); //this is null
return params;
}
In first variant NSLog view non null value, but second variant after block will be nil.
This is because the getJSONFromURLWithString is asynchronous (It uses dispatch_async to make the request call) which means it will be called on another thread while the current thread will keep running.
Your NSLog shows nil since the block is probably executed some time after the NSLog line is reached due to the asynchronous nature of the call (as URL requests take some time to complete and are not immediate)
What you should do is to not use a return-statement, but making your own block where the value is returned. Like this:
in .h:
-(void)getParamsSuccess:(void(^)(Params* params))success;
in .m:
-(void)getParamsSuccess:(void(^)(Params *))success; {
//make post, get requests
[JSONHTTPClient getJSONFromURLWithString:#"http://www.blankspot.ru/api/getinterval"
params:nil
completion:^(id json, JSONModelError *err) {
NSLog(#"json = %#", json);
NSLog(#"Error = %#", err );
NSDictionary* json1 = json;
NSLog(#" %# ob ", [json1 objectForKey:#"success"]);
Params* params = [[Params alloc] initWithDictionary:json1 error:&err];
NSLog(#"params123 = %#", params); // is not null
success(params); // <-- This will call the handler-block with your params-object as the parameter
}];
}
Your problem is that your completion block is executed asynchronously after some other action (e.g. network request) will be complete (argument name "completion" should have given you a clue).
It means that lines
NSLog(#"params123 = %#", params); //this is null
return params;
will be executed way before your block. And at that point params will still be nil.
If you need to process received data, you should do it inside your completion block.
On the other hand, if you need to pass received parameters further, you'll have to create your own completion block parameter, because you get your result (Param *) after other operations are complete and not instantly.
Spoek suggested a good example, but don't forget to check success parameter for not being nil, otherwise when you'll try to call it, your app will crash.
Used this:
-(void)getParams:(void(^)(Params *))finishBlock{
[JSONHTTPClient getJSONFromURLWithString:#"http://www.blankspot.ru/api/getinterval"
params:nil
completion:^(id json, JSONModelError *err) {
NSLog(#"json = %#", json);
NSLog(#"Error = %#", err );
NSDictionary* json1 = json;
NSLog(#" %# ob ", [json1 objectForKey:#"success"]);
params = [[Params alloc] initWithDictionary:json1 error:&err];
finishBlock(params);
NSLog(#"params123 = %#", params); // is not null
}];
}
I am using the following to delete objects using RestKit (0.23.1):
[self.objectManager deleteObject:myObject path:path parameters:nil success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
NSLog(#"success deleting myObject");
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
NSLog(#"failure deleting myObject");
}];
This does create the correct DELETE request and the server returns a 200 status code. However, the local data is not deleted from Core Data. If I do a fetch for the deleted object after the success block above is fired, the fetch returns the object that should be deleted.
The documentation reads:
RKManagedObjectRequestOperation adds special behavior to DELETE
requests. Upon retrieving a successful (2xx status code) response for
a DELETE, the operation will invoke deleteObject: with the operations
targetObject on the managed object context. This will delete the
target object from the local store in conjunction the successfully
deleted remote representation.
Doing a little spelunking it looks like -[RKManagedObjectRequestOperation deleteTargetObject:] is not being called. It seems that it should be called by -[RKManagedObjectRequestOperation willFinish].
It seems like there may be a logic error in the gating if statement in -[RKManagedObjectRequestOperation willFinish].
- (void)willFinish
{
NSMutableIndexSet *deleteableStatusCodes = [NSMutableIndexSet indexSet];
[deleteableStatusCodes addIndex:404]; // Not Found
[deleteableStatusCodes addIndex:410]; // Gone
if (self.error && self.targetObjectID
&& [[[self.HTTPRequestOperation.request HTTPMethod] uppercaseString] isEqualToString:#"DELETE"]
&& [deleteableStatusCodes containsIndex:self.HTTPRequestOperation.response.statusCode]) {
NSError *error = nil;
if (! [self deleteTargetObject:&error]) {
RKLogWarning(#"Secondary error encountered while attempting to delete target object in response to 404 (Not Found) or 410 (Gone) status code: %#", error);
self.error = error;
} else {
if (! [self saveContext:&error]) {
} else {
// All good, clear any errors
self.error = nil;
}
}
}
}
It seems like -[RKManagedObjectRequestOperation willFinish] should be as follows:
- (void)willFinish
{
NSMutableIndexSet *deleteableStatusCodes = [NSMutableIndexSet indexSet];
[deleteableStatusCodes addIndex:404]; // Not Found
[deleteableStatusCodes addIndex:410]; // Gone
[deleteableStatusCodes addIndexes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
if (self.error == nil
&& self.targetObjectID
&& [[[self.HTTPRequestOperation.request HTTPMethod] uppercaseString] isEqualToString:#"DELETE"]
&& [deleteableStatusCodes containsIndex:self.HTTPRequestOperation.response.statusCode]) {
NSError *error = nil;
if (! [self deleteTargetObject:&error]) {
RKLogWarning(#"Secondary error encountered while attempting to delete target object in response to 404 (Not Found) or 410 (Gone) status code: %#", error);
self.error = error;
} else {
if (! [self saveContext:&error]) {
} else {
// All good, clear any errors
self.error = nil;
}
}
}
}
To summarize the changes, I added the successful status codes to the deleteableStatusCodes index set and check to make sure that self.error is equal to nil.
Is my logic change sound, or am I misunderstanding some RestKit convention here? It seems like my logic change aligns with the quoted statement from the documentation.
You're looking in the wrong place. See the line:
success = [weakSelf deleteTargetObject:&error];
In the performMappingOnResponseWithCompletionBlock: method in RKManagedObjectRequestOperation which checks for success status and deletes the object.
The code you have edited is to deal with error responses which, in a nice REST interface, mean the same thing as a DELETE success response.
I've been using AFNetworking 2.0 in my app.
I've noticed that if my web-service returns a 500 status code I do not get the body of the response.
Here is an example of my php code
try
{
$conn = new PDO( "sqlsrv:server=$serverName;Database = $database", $uid, $pwd);
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
return $conn;
}
catch( PDOException $e )
{
$response->status(500);
echo( "Connection Error: " . $e->getMessage() );
}
If I use a simple rest client this is an example of a response body.
Connection Error: SQLSTATE[08001]: [Microsoft][SQL Server Native Client 11.0]SQL Server Network Interfaces: Error Locating Server/Instance Specified [xFFFFFFFF].
However this seems to be the only response I can get from AFNetworking
Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (JSON text did not start with array or object and option to allow fragments not set.) UserInfo=0x15e58fa0 {NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}
This is the part of my objective-c code that does this.
...} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(#"%#",error.description);
}];
Is there a way I can get the response body?
Edit: More code for clarification
Below is part of my subclass of AFHTTPSessionManager
#implementation MSMAMobileAPIClient
+ (MSMAMobileAPIClient *)sharedClient {
static MSMAMobileAPIClient *_sharedClient = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_sharedClient = [[MSMAMobileAPIClient alloc] initWithDefaultURL];
});
return _sharedClient;
}
- (id)initWithDefaultURL {
return [self initWithBaseURL:[NSURL URLWithString:[NSString stringWithFormat:#"https://%#/mamobile/index.php/" ,[[NSUserDefaults standardUserDefaults] stringForKey:#"serviceIPAddress"]]]];
}
- (id)initWithBaseURL:(NSURL *)url {
self = [super initWithBaseURL:url];
if (!self) {
return nil;
}
self.responseSerializer = [AFCompoundResponseSerializer compoundSerializerWithResponseSerializers:#[[AFJSONResponseSerializer serializer], [AFHTTPResponseSerializer serializer]]];
return self;
}
I tried setting the response serializer to a AFCompoundResponseSerializer but it didn't seem to make a difference
Below is an example of a subclass that I call the Librarian.
-(void)searchForItemWithString:(NSString *)searchString withCompletionBlock:(arrayBlock)block {
self.inventorySearchBlock = block;
NSDictionary *parameters = #{#"query": searchString};
[[MSMAMobileAPIClient sharedClient] GET:#"inventory/search" parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject) {
if (!responseObject) {
NSLog(#"Error parsing JSON");
} else {
//do stuff with the json dictionary that's returned..
}
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(#"Error: %#",error.description);
}];
}
UPDATE: I have created a github repository to contain the latest code I am using. All changes will be posted there. https://github.com/Hackmodford/HMFJSONResponseSerializerWithData
The answer comes from this issue on github.
https://github.com/AFNetworking/AFNetworking/issues/1397
gfiumara is the dev who came up with this. I have only slightly modified his subclass of AFJSONResponseSerializer to include an actual string instead of the NSData
//MSJSONResponseSerializerWithData.h
#import "AFURLResponseSerialization.h"
/// NSError userInfo key that will contain response data
static NSString * const JSONResponseSerializerWithDataKey = #"JSONResponseSerializerWithDataKey";
#interface MSJSONResponseSerializerWithData : AFJSONResponseSerializer
#end
// MSJSONResponseSerializerWithData.m
#import "MSJSONResponseSerializerWithData.h"
#implementation MSJSONResponseSerializerWithData
- (id)responseObjectForResponse:(NSURLResponse *)response
data:(NSData *)data
error:(NSError *__autoreleasing *)error
{
if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) {
if (*error != nil) {
NSMutableDictionary *userInfo = [(*error).userInfo mutableCopy];
userInfo[JSONResponseSerializerWithDataKey] = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSError *newError = [NSError errorWithDomain:(*error).domain code:(*error).code userInfo:userInfo];
(*error) = newError;
}
return (nil);
}
return ([super responseObjectForResponse:response data:data error:error]);
}
#end
Here is an example of how I use it in the failure block.
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(#"%#",[error.userInfo objectForKey:#"JSONResponseSerializerWithDataKey"]);
}];
You need to use AFCompoundSerializer to tell the AFNetworking framework how to process all of the possible responses it could receive. By default it will only try to map JSON. A compound serializer will work through the serializers until it finds one that doesn't raise an error.
You want to use:
+ (instancetype)compoundSerializerWithResponseSerializers:(NSArray *)responseSerializers
on AFCompoundResponseSerializer (in AFURLResponseSerialization.h).
You need to pass an array of serializers that can handle the response. One of the serializers in the array should be an instance of AFHTTPResponseSerializer to handle your error responses.
If you include my category in your project, it's as simple as the following:
[mySessionManager POST:#"some-api" parameters:params success:^(NSURLSessionDataTask *task, NSDictionary *responseObject) {
...
} failure:^(NSURLSessionDataTask *task, NSError *error) {
id responseObject = error.userInfo[kErrorResponseObjectKey];
... do something with the response ...
}];
Here's the code for my category. It swizzles AFURLSessionManager to inject a shim into the completion handler. The shim puts the response into the NSError's userInfo.
https://gist.github.com/chrishulbert/35ecbec4b37d36b0d608
I've been using AFNetworking 2.0 in my app.
I've noticed that if my web-service returns a 500 status code I do not get the body of the response.
Here is an example of my php code
try
{
$conn = new PDO( "sqlsrv:server=$serverName;Database = $database", $uid, $pwd);
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
return $conn;
}
catch( PDOException $e )
{
$response->status(500);
echo( "Connection Error: " . $e->getMessage() );
}
If I use a simple rest client this is an example of a response body.
Connection Error: SQLSTATE[08001]: [Microsoft][SQL Server Native Client 11.0]SQL Server Network Interfaces: Error Locating Server/Instance Specified [xFFFFFFFF].
However this seems to be the only response I can get from AFNetworking
Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (JSON text did not start with array or object and option to allow fragments not set.) UserInfo=0x15e58fa0 {NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}
This is the part of my objective-c code that does this.
...} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(#"%#",error.description);
}];
Is there a way I can get the response body?
Edit: More code for clarification
Below is part of my subclass of AFHTTPSessionManager
#implementation MSMAMobileAPIClient
+ (MSMAMobileAPIClient *)sharedClient {
static MSMAMobileAPIClient *_sharedClient = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_sharedClient = [[MSMAMobileAPIClient alloc] initWithDefaultURL];
});
return _sharedClient;
}
- (id)initWithDefaultURL {
return [self initWithBaseURL:[NSURL URLWithString:[NSString stringWithFormat:#"https://%#/mamobile/index.php/" ,[[NSUserDefaults standardUserDefaults] stringForKey:#"serviceIPAddress"]]]];
}
- (id)initWithBaseURL:(NSURL *)url {
self = [super initWithBaseURL:url];
if (!self) {
return nil;
}
self.responseSerializer = [AFCompoundResponseSerializer compoundSerializerWithResponseSerializers:#[[AFJSONResponseSerializer serializer], [AFHTTPResponseSerializer serializer]]];
return self;
}
I tried setting the response serializer to a AFCompoundResponseSerializer but it didn't seem to make a difference
Below is an example of a subclass that I call the Librarian.
-(void)searchForItemWithString:(NSString *)searchString withCompletionBlock:(arrayBlock)block {
self.inventorySearchBlock = block;
NSDictionary *parameters = #{#"query": searchString};
[[MSMAMobileAPIClient sharedClient] GET:#"inventory/search" parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject) {
if (!responseObject) {
NSLog(#"Error parsing JSON");
} else {
//do stuff with the json dictionary that's returned..
}
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(#"Error: %#",error.description);
}];
}
UPDATE: I have created a github repository to contain the latest code I am using. All changes will be posted there. https://github.com/Hackmodford/HMFJSONResponseSerializerWithData
The answer comes from this issue on github.
https://github.com/AFNetworking/AFNetworking/issues/1397
gfiumara is the dev who came up with this. I have only slightly modified his subclass of AFJSONResponseSerializer to include an actual string instead of the NSData
//MSJSONResponseSerializerWithData.h
#import "AFURLResponseSerialization.h"
/// NSError userInfo key that will contain response data
static NSString * const JSONResponseSerializerWithDataKey = #"JSONResponseSerializerWithDataKey";
#interface MSJSONResponseSerializerWithData : AFJSONResponseSerializer
#end
// MSJSONResponseSerializerWithData.m
#import "MSJSONResponseSerializerWithData.h"
#implementation MSJSONResponseSerializerWithData
- (id)responseObjectForResponse:(NSURLResponse *)response
data:(NSData *)data
error:(NSError *__autoreleasing *)error
{
if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) {
if (*error != nil) {
NSMutableDictionary *userInfo = [(*error).userInfo mutableCopy];
userInfo[JSONResponseSerializerWithDataKey] = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSError *newError = [NSError errorWithDomain:(*error).domain code:(*error).code userInfo:userInfo];
(*error) = newError;
}
return (nil);
}
return ([super responseObjectForResponse:response data:data error:error]);
}
#end
Here is an example of how I use it in the failure block.
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(#"%#",[error.userInfo objectForKey:#"JSONResponseSerializerWithDataKey"]);
}];
You need to use AFCompoundSerializer to tell the AFNetworking framework how to process all of the possible responses it could receive. By default it will only try to map JSON. A compound serializer will work through the serializers until it finds one that doesn't raise an error.
You want to use:
+ (instancetype)compoundSerializerWithResponseSerializers:(NSArray *)responseSerializers
on AFCompoundResponseSerializer (in AFURLResponseSerialization.h).
You need to pass an array of serializers that can handle the response. One of the serializers in the array should be an instance of AFHTTPResponseSerializer to handle your error responses.
If you include my category in your project, it's as simple as the following:
[mySessionManager POST:#"some-api" parameters:params success:^(NSURLSessionDataTask *task, NSDictionary *responseObject) {
...
} failure:^(NSURLSessionDataTask *task, NSError *error) {
id responseObject = error.userInfo[kErrorResponseObjectKey];
... do something with the response ...
}];
Here's the code for my category. It swizzles AFURLSessionManager to inject a shim into the completion handler. The shim puts the response into the NSError's userInfo.
https://gist.github.com/chrishulbert/35ecbec4b37d36b0d608