AFJSONRequestOperation returns null response in iOS - json

I am facing 1 problem while using AFJSONRequestOperation. My API Client is as follows
#import <Foundation/Foundation.h>
#import "AFHTTPClient.h"
#import "AFJSONRequestOperation.h"
#interface MyAPIClient : AFHTTPClient
+ (MyAPIClient *)sharedAPIClient;
#end
// .m file
#import "MyAPIClient.h"
#implementation MyAPIClient
+ (MyAPIClient *)sharedAPIClient {
static MyAPIClient *sharedClient = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedClient = [[MyAPIClient alloc] initWithBaseURL:[NSURL URLWithString:kBASE_URL]];
});
return sharedClient;
}
- (id)initWithBaseURL:(NSURL *)url {
self = [super initWithBaseURL:url];
if (!self) {
return nil;
}
[self registerHTTPOperationClass:[AFJSONRequestOperation class]];
[self setDefaultHeader:CONTENT_TYPE_FIELD value:CONTENT_TYPE_JSON_VALUE];
self.parameterEncoding = AFJSONParameterEncoding;
return self;
}
#end
Now when I request with following code it returns me "null" response
NSDictionary *params = [[NSDictionary alloc]initWithObjectsAndKeys:userName,#"email",password,#"password",nil];
NSMutableURLRequest *request = [[MyAPIClient sharedAPIClient] requestWithMethod:#"POST" path:#"login" parameters:params];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON)
{
NSDictionary *dictResponse = (NSDictionary*)JSON;
DLog(#"Login Success JSON: %#",JSON);
if (block) {
block(YES,nil);
}
}failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
DLog(#"Login Error:- %#",error);
if (block) {
block(NO,error);
}
}];
[operation start];
But when I use AFHTTPRequestOperation it reurns me correct output with logged in used info
NSURL *loginUrl = [NSURL URLWithString:kBASE_URL];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:loginUrl];
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
userName,#"email",password,#"password",nil];
NSMutableURLRequest *request = [httpClient requestWithMethod:#"POST" path:#"login" parameters:params];
//Notice the different method here!
AFHTTPRequestOperation *operation = [httpClient HTTPRequestOperationWithRequest:request
success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSLog(#"Raw data Response: %#", responseObject);
NSMutableArray *jsonArray = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:nil];
NSLog(#"Converted JSON : %#", jsonArray);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error){
NSLog(#"Error: %#", error);
}];
//Enqueue it instead of just starting it.
[httpClient enqueueHTTPRequestOperation:operation];
My server returns JSON response.
What is the problem in above code? Why AFJSONRequestOperation returns null response while
AFHTTPRequestOperation returns me correct response ? Any kind of help is appreciated. Thanks in advance

Related

AFNetworking, NSURLSession and json Response (Ronak Sankhala)

I am trying to get json response from a web-service api. I want to extract product data from the json. I also want to implement this using AFNetworking and i also trying to get response using NSURLSession and its completely working.
viewController.h
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController <UITableViewDataSource, UITableViewDelegate>
#property (weak, nonatomic) IBOutlet UITableView *tblTableView;
- (IBAction)btnClickedPostData:(id)sender;
#end
viewController.m
#import "ViewController.h"
#import "AFNetworking.h"
#import "ResponseTableViewCell.h"
#interface ViewController ()
{
NSMutableDictionary *dictArray;
NSMutableArray *dataArray;
}
#end
#implementation ViewController
static NSString *CellIdentifier = #"cell";
- (void)viewDidLoad {
[super viewDidLoad];
[self.tblTableView registerNib:[UINib nibWithNibName:#"ResponseTableViewCell" bundle:nil] forCellReuseIdentifier:#"ResponseTableViewCell"];
[self connectionString];
}
-(void)connectionString
{
//NSURL *URL = [NSURL URLWithString:#"Your URL"];
NSURLSession *session = [NSURLSession sharedSession]; // its working
NSURLSessionDataTask *dataTask = [session dataTaskWithURL:[NSURL URLWithString:#"YOUR URL"] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSMutableDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(#"%#", jsonResponse);
dataArray = [jsonResponse objectForKey:#"objEventcategoryList"];
self.tblTableView.dataSource = self;
self.tblTableView.delegate = self;
[self.tblTableView reloadData];
NSLog(#"JSON: %#", dataArray);
}];
[dataTask resume];
// AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; // its working
// [manager GET:URL.absoluteString parameters:nil progress:nil success:^(NSURLSessionTask *task, id responseObject) {
//
// NSMutableDictionary *jsonResponse = (NSMutableDictionary *)responseObject;
// dataArray = [jsonResponse objectForKey:#"objEventcategoryList"];
//
// self.tblTableView.dataSource = self;
// self.tblTableView.delegate = self;
//
// [self.tblTableView reloadData];
//
// NSLog(#"TableView: %#", _tblTableView);
//
//
// NSLog(#"JSON: %#", dataArray);
// } failure:^(NSURLSessionTask *operation, NSError *error) {
// NSLog(#"Error: %#", error);
// }];
}
#pragma marrk
#pragma marrk - TableView DataSource and Deleget
#pragma marrk
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [dataArray count];// its not working
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
ResponseTableViewCell *cell = (ResponseTableViewCell *)[tableView dequeueReusableCellWithIdentifier:#"ResponseTableViewCell"];
dictArray = [dataArray objectAtIndex:indexPath.row];
//cell.lblCatID.text = [dictArray objrct:#""];
cell.lblCatID.text = [NSString stringWithFormat:#"%#", [dictArray valueForKey:#"EventCategoryId"]];
cell.lblEventName.text = [NSString stringWithFormat:#"%#", [dictArray valueForKey:#"EventCategoryName"]];
cell.lblCreateDate.text = [NSString stringWithFormat:#"%#", [dictArray valueForKey:#"CreatedDate"]];
cell.layoutMargins = UIEdgeInsetsZero;
return cell;
}
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
if ([tableView respondsToSelector:#selector(setSeparatorInset:)])
{
[tableView setSeparatorInset:UIEdgeInsetsZero];
}
if ([tableView respondsToSelector:#selector(setLayoutMargins:)])
{
[tableView setLayoutMargins:UIEdgeInsetsZero];
}
if ([cell respondsToSelector:#selector(setLayoutMargins:)])
{
[cell setLayoutMargins:UIEdgeInsetsZero];
}
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 144.0;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)btnClickedPostData:(id)sender {
NSString *tokenString = #"65d188d3f0ab52487001c331584ac819";
NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
[defaultConfigObject setHTTPAdditionalHeaders:#{ #"token" : tokenString}];
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration:defaultConfigObject delegate:nil delegateQueue:[NSOperationQueue mainQueue]];
NSURL *url = [NSURL URLWithString:#"YOUR URL"];
NSString *paramString = #"lang=en&title=&start=&end=";
NSData *httpBody = [paramString dataUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
[urlRequest setTimeoutInterval:60.0];
NSString *msgLength = [NSString stringWithFormat:#"%lu", (unsigned long)[httpBody length]];
[urlRequest addValue: #"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[urlRequest addValue: msgLength forHTTPHeaderField:#"Content-Length"];
[urlRequest setHTTPMethod:#"POST"];
//[urlRequest setAllHTTPHeaderFields:paramString];
[urlRequest setAllHTTPHeaderFields:#{ #"token" : tokenString}];
[urlRequest setHTTPBody:httpBody];
//[urlRequest setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]];
NSURLSessionDataTask *dataTask = [defaultSession dataTaskWithRequest:urlRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
{
NSError *parseError = nil;
NSHTTPURLResponse* respHttp = (NSHTTPURLResponse*) response;
if (!error && respHttp.statusCode == 200) {
NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
NSMutableArray *arrArray = [responseDictionary objectForKey:#"newslist"];
NSString *title = [NSString stringWithFormat:#"%#", [arrArray valueForKey:#"title"]];
UIAlertView *alert =[[UIAlertView alloc] initWithTitle:#"Details" message:title delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:#"Cancel", nil];
[alert show];
NSLog(#"%#", arrArray);
}else{
NSLog(#"%#", error);
}
}];
[dataTask resume];
}
#end
//CustomeTableviewCell With XIB
**ResponseTableViewCell.h**
#import <UIKit/UIKit.h>
#interface ResponseTableViewCell : UITableViewCell
#property (weak, nonatomic) IBOutlet UILabel *lblCatID;
#property (weak, nonatomic) IBOutlet UILabel *lblEventName;
#property (weak, nonatomic) IBOutlet UILabel *lblCreateDate;
#end
**ResponseTableViewCell.m**
#import "ResponseTableViewCell.h"
#implementation ResponseTableViewCell
#synthesize lblCatID,lblEventName,lblCreateDate;
- (void)awakeFromNib {
[super awakeFromNib];
// Initialization code
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
#end
// and also download and check JSON demo : https://drive.google.com/open?id=0B0rS2ZVDMVRiSmJJb1BuQklJSzA[Click to show JSON demo Hear][1]
//add custom table view cell with custom table cell and add label to display information. i used pod to setup AFNetworking.
and also download and check JSON demo : https://drive.google.com/open?id=0B0rS2ZVDMVRiSmJJb1BuQklJSzAClick to show JSON demo Hear
Can anyone suggest a way to do this.me how the things will be done.
You Can use also use sqlite for the data.

Invalid type in JSON write (NSConcreteMutableData)

I am trying to send a JSON request with AFNetworing but following code giving me JSON text did not start with array or object and option to allow fragments not set error:
NSString *post = [[NSString alloc] initWithFormat:
#"{\"request\":\"login\",\"userName\":\"%#\",\"password\":\"%#\"}", userName, password];
NSData *parameters = [post dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *parameterDictionary =
[NSJSONSerialization JSONObjectWithData:parameters options:NSJSONReadingAllowFragments error:nil];
DDLogDebug(#"Data: %#", [parameterDictionary description]);
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
AFHTTPRequestOperation *operation =
[manager POST:WEB_SERVICE_URL parameters:parameterDictionary
success:^(AFHTTPRequestOperation *operation, id responseObject) {
DDLogDebug(#"LoginView - Success Response: %#", responseObject);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
DDLogError(#"LoginView - Error Response: %#", [error description]);
}];
[operation start];
This is the log output of the parameterDictionary object:
{
password = q;
request = login;
userName = q;
}
I have looked similar questions for the error and tried to put parameters object in to an array but this time I got the error "Invalid type in JSON write (NSConcreteMutableData)"
NSMutableArray *array = [NSMutableArray new];
[array addObject:parameterDictionary];
DDLogDebug(#"Data: %#", [parameterDictionary description]);
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
AFHTTPRequestOperation *operation =
[manager POST:WEB_SERVICE_URL parameters:array
success:^(AFHTTPRequestOperation *operation, id responseObject) {
DDLogDebug(#"LoginView - Success Response: %#", responseObject);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
DDLogError(#"LoginView - Error Response: %#", [error description]);
}];
What I am doing wrong?
UPDATE:
I have tried following but it did't work:
NSMutableDictionary *dictionary = [NSMutableDictionary new];
[dictionary setObject:#"login" forKey:#"request"];
[dictionary setObject:#"q" forKey:#"userName"];
[dictionary setObject:#"q" forKey:#"password"];
DDLogDebug(#"Dictionary: %#", [dictionary description]);
DDLogDebug(#"Json: %#", [dictionary JSONRepresentation]);
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager setRequestSerializer:[AFJSONRequestSerializer serializer]];
AFHTTPRequestOperation *operation =
[manager POST:WEB_SERVICE_URL parameters:dictionary
success:^(AFHTTPRequestOperation *operation, id responseObject) {
DDLogDebug(#"LoginView - Success Response: %#", responseObject);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
DDLogError(#"LoginView - Error Response: %#", [error description]);
}];
UPDATE 2:
This what my AFHTTPRequestOperation look like on error block:
<AFHTTPRequestOperation: 0x7fd881fa1200, state: isFinished, cancelled: NO request: <NSMutableURLRequest: 0x7fd881f9fd60> { URL: http://www.olcayertas.com/services.php }, response: <NSHTTPURLResponse: 0x7fd881d913b0> { URL: http://www.olcayertas.com/services.php } { status code: 200, headers {
Connection = close;
"Content-Length" = 1050;
"Content-Type" = "application/json; charset=utf-8";
Date = "Wed, 21 Jan 2015 10:28:45 GMT";
Server = Apache;
"X-Powered-By" = PleskLin;
} }>
The JSON does not seem to validate on JSONlint.com. I would make sure the JSON is correct from there first.
This is what I entered:
{\"request\":\"login\",\"userName\":\"%#\",\"password\":\"%#\"}
I use this to check the JSON:
if ([NSJSONSerialization isValidJSONObject:requestJSONContents]) { }
I have solved the problem by checking my web service in browser. The problem was in my services.php file. There was an error about log file creation and this error was returning a non JSON response that causing the request to fail. My complate working code is here:
NSMutableDictionary *dictionary = [NSMutableDictionary new];
[dictionary setObject:#"login" forKey:#"request"];
[dictionary setObject:#"q" forKey:#"userName"];
[dictionary setObject:#"q" forKey:#"password"];
DDLogDebug(#"Dictionary: %#", [dictionary description]);
DDLogDebug(#"Json: %#", [dictionary JSONRepresentation]);
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager setRequestSerializer:[AFJSONRequestSerializer serializer]];
[manager setResponseSerializer:[AFJSONResponseSerializer serializer]];
//[manager.securityPolicy setAllowInvalidCertificates:true];
AFHTTPRequestOperation *operation =
[manager POST:WEB_SERVICE_URL parameters:dictionary
success:^(AFHTTPRequestOperation *operation, id responseObject) {
DDLogDebug(#"LoginView - Success Response: %#", responseObject);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
DDLogError(#"LoginView - Error Response: %#", [error description]);
DDLogError(#"Error: %#",operation);
}];
[operation start]
And here is my complate services.php file to make it as a complate example for passing and getting JSON with AFNetworiking and PHP service:
PHP web service that accepts JSON input and return JSON response

AFNetworking 2.0 in AFHTTPRequestOperationManager how to pass HTTPBody tag

I am using AFNetworking 2.0, in this I have to pass json object in body part, How to pass HTTP Body in AFHTTPRequestOperationManager.
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = #{#"foo": #"bar"};
NSURL *filePath = [NSURL fileURLWithPath:#"file://path/to/image.png"];
[manager POST:#"http://example.com/resources.json" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileURL:filePath name:#"image" error:nil];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Success: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
Thanks,
Chatting with you offline, it sounds like the main concern is how to send profile image, name, email address, userid, and password in single request. It might look like:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSURL *filePath = ...
[manager POST:#"http://example.com/registration.json" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileURL:filePath name:#"image" error:nil];
[formData appendPartWithFormData:[name dataUsingEncoding:NSUTF8StringEncoding] name:#"name"];
[formData appendPartWithFormData:[email dataUsingEncoding:NSUTF8StringEncoding] name:#"email"];
[formData appendPartWithFormData:[userid dataUsingEncoding:NSUTF8StringEncoding] name:#"userid"];
[formData appendPartWithFormData:[password dataUsingEncoding:NSUTF8StringEncoding] name:#"password"];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Success: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
No JSON is needed.
If you wanted to use JSON, you can do that, but you wouldn't use the constructingBodyWithBlock method (which creates a multipart/form-data request). Instead, you'd just create a plain old JSON request, e.g.:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
NSDictionary *parameters = #{
#"name" : name,
#"email" : email,
#"userid" : userid,
#"password" : password,
#"image" : base64EncodedImage
};
[manager POST:#"http://example.com/registration.json" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Success: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
Clearly, these are very different approaches, so whatever approach you adopt requires that the server code be written to handle the same API.

JSON params POST not recognize with AFNetworking

[Solved]
I'm trying to edit AFHTTPClient.m to make it work with POST Method in
-(NSMutableURLRequest *)requestWithMethod:(NSString *)method
path:(NSString *)path
parameters:(NSDictionary *)parameters
like this :
if ([method isEqualToString:#"GET"] ||[method isEqualToString:#"POST"] || [method isEqualToString:#"HEAD"] || [method isEqualToString:#"DELETE"])
I have problem with POST method with params userDevice ,I have function subclass from AFHTTPClient like this
EDIT:
I used different method like this but same result
-(void)loginWithEmail:(NSString *)email password:(NSString *)passwords
{
NSString *baseurl = #"http://localhost.com:9000/";
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:baseurl]];
[httpClient registerHTTPOperationClass:[AFJSONRequestOperation class]];
[httpClient setDefaultHeader:#"Accept" value:#"application/json"];
[httpClient setAuthorizationHeaderWithUsername:email password:passwords];
and then this is my params :
NSDictionary *data = [NSDictionary dictionaryWithObjectsAndKeys:
model, #"deviceModel",
systemVersion, #"deviceVersion",
[NSNumber numberWithBool:0], #"productionMode",
appVersion, #"appVersion",
deviceType,#"deviceType", nil];
NSError *error = nil;
NSDictionary* jsonObject = [NSDictionary dictionaryWithObjectsAndKeys:data, #"userDevice", nil];
NSData *jsonLogin =[NSJSONSerialization dataWithJSONObject:jsonObject options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonLoginString = [[NSString alloc] initWithData:jsonLogin encoding:NSUTF8StringEncoding];
NSLog(#"JSON LOGIN OUTPUT :%#", jsonLoginString);
[httpClient setParameterEncoding:AFJSONParameterEncoding];
I request using this code :
NSMutableURLRequest *request = [httpClient requestWithMethod:#"POST"
path:#"/ios/login"
parameters:[NSDictionary dictionaryWithObjectsAndKeys:jsonLoginString,#"userDevice", nil]
];
AFJSONRequestOperation *operation = nil;
operation = [AFJSONRequestOperation
JSONRequestOperationWithRequest:request
success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
NSLog(#"Response : %#", request);
NSLog(#"JSON: %#",JSON);
}
failure:^(NSURLRequest *request , NSHTTPURLResponse *response, NSError *error , id JSON ){
NSLog(#"error: %#", error);
}];
[operation start];
this is the example json that I wanted :
"userDevice" : {
"appVersion" : "1.0",
"deviceModel" : "iPhone Simulator",
"productionMode" : false,
"deviceType" : "iPhone Simulator",
"deviceVersion" : "6.1"
}
am I missing something?

receiving the error response with AFHTTPClient calls

I'm implementing AFHTTPClient as a singleton class, as recommended in the docs, and calling that with JSON data in a post, and receiving JSON data in return:
[[BMNetworkCalls sharedInstance] postPath:theURL parameters:theDict success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"my return is: %#", [responseObject valueForKeyPath:#"Result"]);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"error in network call: %#", [error localizedDescription]);
}];
All fine and good, but if I receive an error, ("error in HTTPRequestOperation: Expected status code in (200-299), got 400"), I actually want to read the responseObject here as well (this is the way the API I am using tells me what class of error I caused).
I could do that using AFJSONRequestOperation:
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
NSLog(#"my return is: %#", [JSON valueForKeyPath:#"Result"]);
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
NSLog(#"exception code: %#", [JSON valueForKeyPath:#"ExceptionCode"]);
NSLog(#"exception message: %#", [JSON valueForKeyPath:#"ExceptionMessage"]);
}];
[operation start];
How can I (and can I?) do it using AFHTTPClient?
The operation variable has everything that you need:
[[BMNetworkCalls sharedInstance] postPath:theURL parameters:theDict success:^(AFHTTPRequestOperation *operation, id responseObject) {
// ...
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
if ([operation isKindOfClass:[AFJSONRequestOperation class]]) {
id JSON = [(AFJSONRequestOperation *)operation responseJSON];
NSLog(#"JSON: %#", JSON)
}
}];
All credit goes to #phix23, who pointed me in the correct direction!
Here is the custom method I wrote in my subclassed AFHTTPClient that allows me to see the JSON response after receiving a 400 error:
- (void) myPostPath:(NSString *)path
parameters:(NSDictionary *)parameters
success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, id JSON))success
failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON))failure
{
NSURLRequest *request = [self requestWithMethod:#"POST" path:path parameters:parameters];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:success failure:failure];
[self enqueueHTTPRequestOperation:operation];
}
I call it by:
[[BMNetworkCalls sharedInstance] myPostPath:theURL parameters:theDict success:^(NSURLRequest *request, NSHTTPURLResponse *response, id responseObject) {
NSLog(#"my return is: %#", [responseObject valueForKeyPath:#"Result"]);
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
NSLog(#"exception code: %#", [JSON valueForKeyPath:#"ExceptionCode"]);
}];