AFNetworking POST Request not working? - ios

This question is already answered at many places but no solution is working for me! I m using code for AFNetworking as following
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer=[AFJSONResponseSerializer serializer];
NSDictionary *parameters=#{#"Key1":#"Value1",#"Key2":#"Value2"};
// NSDictionary *parameters = #{#"foo": #"bar"};
[manager POST:#"https://www.MyURL.com/index.php" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
Error :
Error: Error Domain=NSURLErrorDomain Code=-1012 "The operation couldn’t be completed. (NSURLErrorDomain error -1012.)" UserInfo=0x7a2a03b0 {NSErrorFailingURLKey=https://www.MyURL.com/index.php, NSErrorFailingURLStringKey=https://www.MyURL.com/index.php}
I got no luck for above request.
I do not know what is wrong with my code in POST Request, GET Request is working fine in the AFNetworking.

Try this one :
NSDictionary *dictParameters = parameter here
//create url
NSString *strURL = [NSString stringWithFormat:#"url here"];
NSLog(#"loginurl : %#",strURL);
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
AFHTTPRequestOperation *apiRequest = [manager POST:strURL parameters:dictParameters success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSData *jsonData = (NSData *)responseObject;
NSError * parsedError = nil;
id *value = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:&parsedError];
if (parsedError == nil)
{
//Successfull
}
else
{
NSLog(#"wrong while parsing json data");
}
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
NSLog(#"Error : %#",[error description]);
}];
//start request right now
[apiRequest start];
EDIT : Just Formatted

Related

Array In Post Data Afnetworking Gives Error - Required Data Missing

Hii I am using afnetworking from post array data to sent server side here is my code ...
NSMutableDictionary *dict1=[[NSMutableDictionary alloc]initWithObjectsAndKeys:#"online_status",#"option_name",dict[#"option_value"],#"option_value", nil];
NSArray *arr1=[[NSMutableArray alloc]initWithObjects:dict1, nil];
NSMutableDictionary *dict2=[[NSMutableDictionary alloc]initWithObjectsAndKeys:[UserDefaults valueForKey:#"user_id"],#"user_id",arr1,#"option_array", nil];
NSError *error = nil;
NSString *createJSON = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:dict2
options:NSJSONWritingPrettyPrinted
error:&error]
encoding:NSUTF8StringEncoding];
NSDictionary *pardsams = #{#"data": createJSON};
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSLog(#"Dict %#",pardsams[#"data"]);
manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:#"text/html"];
[manager POST:[NSString stringWithFormat:#"%#set_user_multiple_options",K_APP_URL] parameters: pardsams[#"data"] success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
and getting server responce is :
message = "Required parameters missing.";
status = 0;
i will hit the request to rest client but where getting correct responce saved data bt trying to do in code it not working polease... help me

Getting Error While Post Data Using AFnetworking

This is my Code:
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary options:0 error:nil];
NSString *json = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSDictionary *dict = #{#"body":json};
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager POST:#"http://abc/" parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSString *myString = [[NSString alloc] initWithData:operation.request.HTTPBody encoding:NSUTF8StringEncoding];
NSLog(#"Error: %#", myString);
}];
But i am Getting Error Like This
body=%7B%22pincode%22%3A%22gfgfgf%22%2C%22mobile%22%3A%221111%22%2C%22password%22%3A%22rwerew%22%2C%22profile_pic%22%3A%22%22%2C%22social_accesstoken%22%3A%22%22%2C%22sponsor_choice%22%3A3%2C%22sponsor_id%22%3A%22%22%2C%22social_provider%22%3A%22Normal%22%2C%22email%22%3A%22ghffh%22%2C%22gender%22%3A1%2C%22name%22%3A%22narendra%22%2C%22nickname%22%3A1233%2C%22country%22%3A%22Japan%20%28JPY%29%22%2C%22fromLogin%22%3A%22%22%2C%22methodName%22%3A%22signup%22%2C%22birth_date%22%3A%2208-06-01%22%7D
Can any one suggest me on this kind...
There is no need to convert error to encoded string....
First of all clear that.. which type of parameter you needed..
and then try this code for simple posting data:
(Make related changes according to your parameters needed)
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
NSDictionary *param = # {#"body":json};
[manager POST:URL_HERE parameters:param
success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSLog(#"JSON: %#", responseObject);
}
failure:
^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];

AFNetworking 2.0 Send Post Request with array of dictionary Parameters

I want to try post parameter in the following API but the parameter is not getting passed properly, and the response received gives the message that, data is required. So can anyone please help to sort out this problem.
my url is
forapp.com/api/getContacts.php?data=[
{"name":"abc","phone":"1234567890"},{"name":"Kate
Bell","phone":"9925992599"} ]
so how i can pass this type of request to the api
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *params = #{#"name": #"hello",
#"phone": #"1234567890"};
NSLog(#"Dict %#",params);
manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:#"text/html"];
[manager POST:#"http://forapp.com/api/getContacts.php" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
just add
Step-1
// create the dictionary of {"name":"abc","phone":"1234567890"},{"name":"Kate Bell","phone":"9925992599"} this
NSDictionary *params = #{#"name": #"hello",
#"phone": #"1234567890"};
Step-2
//create the one array of this output [ {"name":"abc","phone":"1234567890"},{"name":"Kate Bell","phone":"9925992599"} ]
NSMutableArray *arr = [NSMutableArray arrayWithObjects:params,nil];
Step-3
// convert your object to JSOn String
NSError *error = nil;
NSString *createJSON = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:objectsInCart
options:NSJSONWritingPrettyPrinted
error:&error]
encoding:NSUTF8StringEncoding];
Step-4
//create the another one dictionary for send the data for like data=[ {"name":"abc","phone":"1234567890"},{"name":"Kate Bell","phone":"9925992599"} ]
NSDictionary *pardsams = #{#"data": createJSON};
Step-5
// finally start your request
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSLog(#"Dict %#",pardsams);
manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:#"text/html"];
[manager POST:#"http://forapp.com/api/getContacts.php" parameters:pardsams success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
as per this url
forapp.com/api/getContacts.php?data=[ {"name":"abc","phone":"1234567890"},{"name":"Kate Bell","phone":"9925992599"} ]
You should implement like this
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *params = #{#"name": #"hello",
#"phone": #"1234567890"};
NSLog(#"Dict %#",params);
manager.responseSerializer = [AFJSONResponseSerializer serializer];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:#"text/html"];
[manager POST:#"http://forapp.com/api/getContacts.php" parameters:#{#"data": #[params]} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
Add following:
// httpClient is a subclass of AFHTTPRequestOperationManager or AFHTTPSessionManager
httpClient.requestSerializer = AFJSONRequestSerializer;
And also check your post array does not include any other object. It just include array.

AFNetworking not receiving response data

I am using AFNetworking to GET request by posting json object. But i am receiving empty value. I am using the following code.
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
NSDictionary *params = # {#"email" :user_name, #"password" :pass_word };
[manager GET:HOST_URL parameters:params
success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSLog(#"JSON: %#", responseObject);
NSDictionary *weather = (NSDictionary *)responseObject;
}
failure:
^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
NSLog(#"opstr%#",operation.responseString);
}];
What method i should use. If i use POST, i am getting error saying that "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.)
When i use GET i am getting response as empty. I am not sure where i am wrong.
Thanks in advance.
It means that your request response is not a valid json. You can correct the web service to return proper json. Or remove the following line
manager.requestSerializer = [AFJSONRequestSerializer serializer];
because it is converting response to json.
To allow fragments, change the code to following
[manager GET:HOST_URL parameters:params
success:^(AFHTTPRequestOperation *operation, id responseObject)
{
id json = [NSJSONSerialization JSONObjectWithData:responseObject
options:NSJSONReadingAllowFragments
error:&deserializingError];
NSLog(#"JSON: %#", responseObject);
NSDictionary *weather = (NSDictionary *)responseObject;
}
failure:
^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
NSLog(#"opstr%#",operation.responseString);
}];

responseObject is not JSON but NSInLineData for AFHTTPRequestOperationManager

Following code is to submit images through an operationQueue. The requests are all fired one by one correctly, the server response contains the image file name which client needs to get hold of. The problem is that the reponseObject for the success/failure block is not expected parsed JSON but type of NSInLineData shown in debugger. Now I suspect the code to construct the operation from the NSMutableURLRequest caused the issue. Please help.
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
NSMutableURLRequest *request = [manager.requestSerializer multipartFormRequestWithMethod:#"POST"
URLString:podURLString parameters:nil
constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
NSError *error;
BOOL success =[formData appendPartWithFileURL:imgURL name:#"images" fileName:img.path
mimeType:#"image/jpg" error:nil];
if (!success)
NSLog(#"appendPartWithFileURL error: %#", error);} error:nil];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Image Success: %#", [responseObject description]);
NSString *imagePath = [response objectForKey:#"imageFileName"];
[self.delegate networkManager:self didSubmitDeliveryImageForImageID:imagePath];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Image Error: %#", error);
NSLog(#"image error: %#", [operation.responseObject description]);
NSString *imageFilePath = [operation.responseObject objectForKey:#"imageFileName"];
[self.delegate networkManager:self didFailSubmitDeliveryImageForImageID:imageFilePath];
}];
[manager.operationQueue addOperation:operation];
When you get the response as NSInLineData. It's good to go now. You can write below single line of code to get NSDictionary if it supports json format.
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:responseObjec options:0 error:nil];
Just add this line of code before your AFHTTPRequestOperation block
**operation.responseSerializer = [AFJSONResponseSerializer serializer];**

Resources