Array In Post Data Afnetworking Gives Error - Required Data Missing - ios

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

Related

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.

Unable to post JSON Using afnetworking in ios

I am getting this error while posting json to url :
Invalid top-level type in JSON write'
I am even sending perfect JSON using afnetworking post request code But it keeps giving me error.
My code :
NSString * serviceType = #"xyz";
NSString * remarks =#"project deadline is near ";
NSString * emailId = #"xyx.live.com";
NSDictionary *params =
# {
#"serviceType" :serviceType,
#"remarks" :remarks,
#"emailId" :emailId
};
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params
options:0
error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
AFHTTPRequestOperationManager *manager2 = [AFHTTPRequestOperationManager manager];
AFJSONRequestSerializer *serializer = [AFJSONRequestSerializer serializer];
[serializer setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[serializer setValue:#"application/json" forHTTPHeaderField:#"Accept"];
manager2.requestSerializer = serializer;
[manager2 POST:#"http://xyx.com" parameters:jsonString success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON_post_fzzlogin: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//here is place for code executed in success case
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error while sending POST"
message:#"Sorry, try again."
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alertView show];
NSLog(#"Error: %#", error);
}];
Please help me out this regard .thanks in advance
You are trying to encode request twice because you set request serializer for AFHTTPRequestOperationManager and provide parameters as encoded JSON string. So you need to provide raw parameters if you want to use request serializer or don't use it and encode to JSON manually.
This is how you post JSON or rather NSDictionary by AFNetworking
NSDictionary *dict = #{#"Key":#"Value"};
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager POST:[Util urlAppend:kListOfArticleCatagory] parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSDictionary *responseObj = (NSDictionary *)responseObject;//casting to NSDictionary from id
NSLog(#"%#",responseObj);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Something went wrong :%#",operation.responseString);
}];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"text/html"];
}
You dont post JSON through AFNetworking, rather the NSDictionary as the parameters, it will get converted to JSON as you post it.

iOS : How to correctly send put request to server

I have a put request that I am trying to achieve. The problem I am having is it isn't sending the correct raw body over to the server form/post parameter. What I am expecting is a raw body that is {"questions":[{"type":"control_head"}]}, instead I am getting questions[][type]=control_head any tips or suggestions are appreciated.
NSString *jsonString = #"{\"questions\":[{\"type\":\"control_head\"}]}";
[self createForms:jsonString];
- (void) createForms : (NSString *) form
{
[self executePutRequest:#"user/forms" params:form];
}
- (void) executePutRequest : (NSString *) url params : (NSString *) params
{
NSString *urlStr = [NSString stringWithFormat:#"http://requestb.in/13oujhot"];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSData *data = [params dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSMutableDictionary *userinfo = [[NSMutableDictionary alloc] init];
[manager PUT:urlStr parameters:json success:^(AFHTTPRequestOperation *operation, id responseObject) {
[operation setUserInfo:userinfo];
SBJsonParser *jsonparser = [SBJsonParser new];
id result = [jsonparser objectWithString:[operation responseString]];
if ( self.delegate != nil && [self.delegate respondsToSelector:finishSelector] ) {
[self.delegate performSelector:finishSelector withObject:result];
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
[operation setUserInfo:userinfo];
if ( self.delegate != nil && [self.delegate respondsToSelector:failSelector] ) {
[self.delegate performSelector:failSelector withObject:[operation error]];
}
}];
}
Copied From here
Updated again for AFNetworking 2.0 - see bottom
For AFNetworking 1.0:
NSURL *url = [NSURL URLWithString:#"https://mysite.com/"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
height, #"user[height]",
weight, #"user[weight]",
nil];
[httpClient postPath:#"/myobject" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(#"Request Successful, response '%#'", responseStr);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"[HTTPClient Error]: %#", error.localizedDescription);
}];
For AFNetworking 2.0 (and also using the new NSDictionary syntax):
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *params = #{#"user[height]": height,
#"user[weight]": weight};
[manager POST:#"https://mysite.com/myobject" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
you can use afnetworking framework, it will help you.
http://www.raywenderlich.com/59255/afnetworking-2-0-tutorial
NSString *str_URL = [NSString stringWithFormat:#"YOUR URL"]];
NSDictionary *parameters = [NSDictionary dictionaryWithObjectsAndKeys:
Your Value,KEY_Name,
nil];
AFHTTPRequestOperationManager *Manager = [AFHTTPRequestOperationManager manager];
[Manager PUT:str_URL parameters:parameters
success: ^(AFHTTPRequestOperation *operation, id responseObject)
{
NSLog(#"%#", responseObject);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
NSLog(#"%#", error.description);
}];

AFNetworking POST Request not working?

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

Resources