unable to get response object - ios

I am unable to get the response from api as the response is quite large. Below code gives internal server error but on rest client runs fine.
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
manager.securityPolicy.allowInvalidCertificates = YES;
[manager GET:constantString parameters: nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"POST data JSON returned: %#", responseObject);
jsonArrayNew = responseObject;
[[UIApplication sharedApplication] endIgnoringInteractionEvents];
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
dispatch_async(dispatch_get_main_queue(), ^{
});
});

Related

AFNetworking Couldn't Send JSONData through POST Request?

This is the code I wrote for posting JSON to server.
AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
mgr.requestSerializer = [AFJSONRequestSerializer serializer];
NSLog(#"Dictionary %#",formData);
[mgr POST:[self getFullURL:WSFormSubmit] parameters:formData success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
formData Prints as:
{
FieldValueDTOs = (
{
AdditionalInfo = "";
CreateTime = "2015-09-09 10:14";
FieldValue = "";
ReportFieldValueID = 0;
ReportID = 0;
ReportTemplateFieldID = 21642;
},
{
AdditionalInfo = "";
CreateTime = "2015-09-09 10:14";
FieldValue = asdfasdf;
ReportFieldValueID = 0;
ReportID = 0;
ReportTemplateFieldID = 21643;
}
);
LocationID = 27;
ReportID = 0;
ReportLabel = "";
ReportTemplateID = 930;
ReportTime = "2015-09-09 10:14";
}
This seems to be perfect Dictionary to send it as a parameter to manager's POST:parameters:success method.
But it's returning this error when I do this. I couldn't figure out what's causing the error.
Error log in debugger:
Error: 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=0x79069f90 {NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set., NSUnderlyingError=0x790517c0 "Request failed: bad request (400)"}
formData must be NSDictionary object
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager.requestSerializer setTimeoutInterval:60];
[manager POST:[self getFullURL:WSFormSubmit]
parameters:formData
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString* newStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(#"Response: %#",newStr);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
Hope this works, you can set values for json in header field
AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
AFJSONRequestSerializer *requestSerializer = [AFJSONRequestSerializer serializer];
[requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Accept"];
mgr.requestSerializer = requestSerializer;
[mgr POST:[self getFullURL:WSFormSubmit] parameters:formData success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"application/json"];
[manager POST:"<Your Host URL>" parameters:<Params as Dictionary> success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSError *error = nil;
// *** Perform success action ***
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// *** perform failure action ***
}];
you forgot to set contentType for your request which is JSON and make sure your API accepts JSON and POST data as input otherwise it will not work.

AFNetworking response failure block is called instead of success block

AFNetworking response failure block is being called when I get status code 200. How can I make the success be called instead?
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:#"http://128.199.94.58/test/bt/client_token.php" parameters:nil
success:^(AFHTTPRequestOperation *operation, id responseObject) {
self.clientToken = responseObject[#"customerID"];
NSLog(#"Client Token received.");
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// Handle failure communicating with your server
NSLog(#"Client Token request failed.%#",operation.responseString);
NSLog(#"error code %ld",(long)[operation.response statusCode]);
}];
Look at the value of error. It will tell you why the connection failed. "Failure" in this context has nothing to do with the status code. Returning "404" is still a "success." Failure means you were unable to complete the operation.
use acceptableStatusCodes as follows:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
manager.requestSerializer = [TimeoutAFJSONRequestSerializer serializer];
NSMutableIndexSet* codes = [[NSMutableIndexSet alloc] init];
[codes addIndex: 200];
manager.responseSerializer.acceptableStatusCodes = codes;
[manager GET:urlString parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject)
{
} failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
}];
I run this code and it work find.
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager GET:#"http://128.199.94.58/test/bt/client_token.php" parameters:nil
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseObject
options:kNilOptions
error:nil];
self.clientToken = json[#"customerID"];
NSLog(#"Client Token received.");
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// Handle failure communicating with your server
NSLog(#"Client Token request failed.%#",operation.responseString);
NSLog(#"error code %ld",(long)[operation.response statusCode]);
}];
responce is:
json:
{
customerID = "eyJ2ZXJzaW9uIjoyLCJhdXRob3JpemF0aW9uRmluZ2VycHJpbnQiOiJhMjg2OGVjY2FmZjNjMTQ0M2Y4MTg2MjQ4NDFhZDIyZGM3MWFhO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NldHNVcmwiOiJodHRwczovL2NoZWNrb3V0LnBheXBhbC5jb20iLCJkaXJlY3RCYXNlVXJsIjpudWxsLCJhbGxvd0h0dHAiOnRydWUsImVudmlyb25tZW50Tm9OZXR3b3JrIjp0cnVlLCJlbnZpcm9ubWVudCI6Im9mZmxpbmUiLCJ1bnZldHRlZE1lcmNoYW50IjpmYWxzZSwiYnJhaW50cmVlQ2xpZW50SWQiOiJtYXN0ZXJjbGllbnQzIiwibWVyY2hhbnRBY2NvdW50SWQiOiI2ejl3eGtkanlyNnQzbmg1IiwiY3VycmVuY3lJc29Db2RlIjoiVVNEIn0sImNvaW5iYXNlRW5hYmxlZCI6ZmFsc2UsIm1lcmNoYW50SWQiOiJ6cWQ5ZHBqZmZkc2s3eG55IiwidmVubW8iOiJvZmYifQ==";
}
It may be work for you.
If you check your error in failure block it clearly say that invalid content type. You need to set the content type of the manager as follows
manager.requestSerializer = [AFJSONRequestSerializer serializer];
try this
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
and in success block
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:manager.responseData options:kNilOptions error:nil];
self.clientToken = dic[#"customerID"];
NSLog(#"Client Token received.");
}

AFNetworking POST Value

Here's my question:
NSDictionary *parameters = #{#"type": #"5", #"xq": #"a", #"apid": #"b", #"apsecret": #"c", #"astoken": #"d"};
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer]; manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager.requestSerializer setValue:[NSString stringWithFormat:#"text/plain; charset=UTF-8"] forHTTPHeaderField:#"Content-Type"];
if i use GET :
[manager GET:#"http://127.0.0.1/123.php" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"responseObject : %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"error : %#", error);
}];
i can get $_GET['parameters'] value
but when i use POST :
[manager POST:#"http://127.0.0.1/123.php" parameters:parameters
success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSLog(#"responseObject : %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
NSLog(#"error : %#", error);
}];
i always get $_POST['parameters'] value is null.....
am i doing something wrong in the setting?
Change your 4th line of 1st code snippet to,
[manager.requestSerializer setValue:[AFJSONRequestSerializer serializer]];
sorry for all,
i found it's can work
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:#"http://127.0.0.1/123.php"]];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager POST:#"123.php"
parameters:parameters
success:^(NSURLSessionDataTask *task, id responseObject) {
NSLog(#"responseObject : %#", responseObject);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(#"error : %#", error);
}];

Trying to make a function to handle AFNetworking

I'm trying to make a function that I'll call to handle the AFNetworking JSON parse.
Here is my code:
- (int)startParseWithParameters:(NSDictionary*)incomingParameters andUrlAdress:(NSString*)urlAdress;
{
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
NSDictionary *parameters = incomingParameters;
[manager POST:urlAdress parameters:parameters success:^
(AFHTTPRequestOperation *operation, id responseObject)
{
NSString *recivedErr = responseObject[#"error"];
_errValue = [recivedErr intValue];
NSLog(#"JSON: %d", _errValue);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
NSLog(#"Error: %#", error);
}];
return _errValue;
}
I want the function to return 0 or 1, then I'll know if there is an error or not.
Right now it always return 0.
When I try to return in the success block I get a compiler error.
What could cause this problem?
The succes block is handled async so you should just call a method in the block:
- (void)startParseWithParameters:(NSDictionary*)incomingParameters andUrlAdress:(NSString*)urlAdress {
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
NSDictionary *parameters = incomingParameters;
__weak typeof(self) weakSelf = self;
[manager POST:urlAdress parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *recivedErr = responseObject[#"error"];
[weakSelf didReceiveResponse:[recivedErr integerValue];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
}
-(void)didReceiveResponse:(NSInteger)status {
}

json data parameter changes structure upon reaching php server

I'm working on a mobile app that takes personal information from users then saves it to the php server. I'm having a problem on the data with array of dictionaries, how do I fix this?
The sample data that the mobile app sends to the server looks like this, see the work_experience, it's an array of dictionaries:
Don't mind the data values, it's taken on different times, mind the data structure in work_experience
It becomes like this when it reaches the server:
This is how the work_experience gets saved, which is wrong:
This is my post request:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"text/html"];
[manager POST:SAVE_USER_INFO_URL parameters:_userInformation success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
php function that receives the post request:
$params = $this->params()->fromPost();
$userId = $this->getUsersTable()->saveUserInfo($params);
$this->getSkillsTable()->saveSkills($params['skillset'], $userId);
$this->getWorkExperienceTable()->saveWorkExperience($params['work_experience'], $userId);
$view = new JsonModel($params);
return $view;
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
//manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"text/html"];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager POST:SAVE_USER_INFO_URL parameters:_userInformation success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
You are limiting the app to only accept responses with header text/html, which is not correct because you are looking for json response. And you need to set the requestSerializer to a AFJSONRequestSerializer instance because the default is AFHTTPRequestSerializer

Resources