How to POST data using AFNetworking 2.0?
Does your web service expect the parameters to be formatted as JSON? If so, before you invoke the POST
method, you need to tell the manager
to use a JSON requestSerializer
, i.e. AFJSONRequestSerializer
:
manager.requestSerializer = [AFJSONRequestSerializer serializer];
By default, AFNetworking assumes you want to use AFHTTPRequestSerializer
(i.e. a request with a Content-Type
of application/x-www-form-urlencoded
).
Posting JSON data using AFNetworking 2.0
after searching docs and trying out some codes I got following as an example
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
NSDictionary *params = @ {@"user" :txtUserName, @"pwd" :txtPwd };
[manager POST:URL_SIGNIN parameters:params
success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSLog(@"JSON: %@", responseObject);
}
failure:
^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
Also don't forget to set response header type in the server script as Application/json.
Objective-C How to POST form-data using AFNetworking?
You need to serialize your params dictionary and then string encode it, since your body parameter has a JSON object in it.
Try using this :
NSDictionary *params = @{@"email": @"email@gmail.com", @"name": @"myName"};
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params 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://myURL.com/user" 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);
}];
AFNetworking Post Request
It's first worth adding (as this answer is still popular 6 years after I initially wrote it...) that the first thing you should consider is whether you should even use AFNetworking. NSURLSession was added in iOS 7 and means you don't need to use AFNetworking in many cases - and one less third party library is always a good thing.
For AFNetworking 3.0:
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
NSDictionary *params = @{@"user[height]": height,
@"user[weight]": weight};
[manager POST:@"https://example.com/myobject" parameters:params progress:nil success:^(NSURLSessionTask *task, id responseObject) {
NSLog(@"JSON: %@", responseObject);
} failure:^(NSURLSessionTask *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
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://example.com/myobject" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
If you are stuck using AFNetworking 1.0, you need to do it this way:
NSURL *url = [NSURL URLWithString:@"https://example.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);
}];
AFNetworking 2.0 Send Post Request with array of dictionary Parameters
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);
}];
How to upload binary data using AFNetworking 2.0
I eventually got this to work by using the AFURLSessionManager. Here is the complete code:
NSString *uploadAttachmentURL = @"https://mydomain.zendesk.com/api/v2/uploads.json?filename=screenshot.jpeg";
NSData *imageData = UIImageJPEGRepresentation(image, 1.0);
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
_afHTTPSessionManager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:configuration];
// hack to allow 'text/plain' content-type to work
NSMutableSet *contentTypes = [NSMutableSet setWithSet:_AFOpManager.responseSerializer.acceptableContentTypes];
[contentTypes addObject:@"text/plain"];
_afHTTPSessionManager.responseSerializer.acceptableContentTypes = contentTypes;
[_afHTTPSessionManager.requestSerializer setAuthorizationHeaderFieldWithUsername:@"[USERNAME]" password:@"[PASSWORD]"];
[_afHTTPSessionManager POST:uploadAttachmentURL parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:imageData name:@"screenshot" fileName:@"photo.jpg" mimeType:@"image/jpeg"];
} success:^(NSURLSessionDataTask *task, id responseObject) {
DDLogError(@"screenshot operation success! %@", responseObject);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
DDLogError(@"Operation Error: %@", error);
}];
Related Topics
How to Create Custom Album in Swift 3 iOS 10
Responseserializer 'Cannot Call Value of Non-Function Type 'Nshttpurlresponse'' with Swift 3
Xcode6 Goldmaster Submitting Build Failed with Error
Launching App from Sms Link or Email Link
How to Get Path to a Subfolder in Main Bundle
iOS 8 Code Working on iPhone 5S But Not iPhone 5
Why Wkwebview Doesn't Display Videos? - Swift 3
Uiactivityviewcontroller Subject Not Working for Outlook
Get All Ranges of a Substring in a String in Swift
How to Send Push Notification to Apns from iOS Device
Uitableview Has Unwanted Animation When Reloaddata Is Called
Multiple Lines in UItabbaritem Label
How to Sort Core Data Array Based on Date Entered
How to Show Viewcontroller from a Non-Viewcontroller Helper Class
Uibutton Target Action Inside Uiview
-Costtonode:' Not Sent to Gkgraphnode2D Subclass in Gameplaykit