Afnetworking 2 with parameters - ios

i am really new to IOS developments..i just want to get some JSON response from my web service. when i searched about it i found AFnetworking is good for that. so i downloaded it and did a sample application. but i need to pass some parameters to the service . my service takes two parameters [username and password]. my url like this
http://myweb.mobile.com/WebServices/AppointmentService.asmx/GetValidUser
can anyone please give me some code sample how to pass my parameters to this service to get json response ?
i have tried this code.. but it wont take parameters.. some people telling about AFHTTPClient.. but im using AFN 2.0.. there is no class call AFHTTPCLient here .. i'm so conduced here....please help me
NSURL *url = [NSURL URLWithString:#"https://maps.googleapis.com/maps/api/place/textsearch/json?query=restuarants+in+sydney&sensor=false&key=AIzaSyDn9a-EvJ875yMxZeINmUP7CwbO9YT1w2s"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// 2
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
// 3
self.googlePlaces = [responseObject objectForKey:#"results"];
[self.tableView reloadData];
// NSLog(#"JSON RESULT %#", responseObject);
self.weather = (NSDictionary *)responseObject;
self.title = #"JSON Retrieved";
[self.tableView reloadData];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// 4
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error Retrieving Weather"
message:[error localizedDescription]
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alertView show];
}];
// 5
[operation start];
EDIT :
i have sloved my problem using below code segments...
NSDictionary *parameters = [[NSDictionary alloc] initWithObjectsAndKeys:#"47", #"caregiverPersonId", nil];
AFSecurityPolicy *policy = [[AFSecurityPolicy alloc] init];
[policy setAllowInvalidCertificates:YES];
AFHTTPRequestOperationManager *operationManager = [AFHTTPRequestOperationManager manager];
[operationManager setSecurityPolicy:policy];
operationManager.requestSerializer = [AFJSONRequestSerializer serializer];
operationManager.responseSerializer = [AFJSONResponseSerializer serializer];
[operationManager POST:#"your full url goes here"
parameters:parameters
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", [responseObject description]);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", [error description]);
}
];

Try this
-(void)login
{
NSMutableDictionary *dict=[[NSMutableDictionary alloc]initWithCapacity:3];
[dict setObject:_usernameTextField.text forKey:#"userName"];
[dict setObject:_passwordTextField.text forKey:#"password"];
AFHTTPClient *client=[[AFHTTPClient alloc]initWithBaseURL:[NSURL URLWithString:#""]];
[client registerHTTPOperationClass:[AFJSONRequestOperation class]];
[client setDefaultHeader:#"Accept" value:#"application/json"];
client.parameterEncoding = AFJSONParameterEncoding;
[client postPath:#"GetValidUser" parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSDictionary *op=(NSDictionary *)responseObject;
NSLog(#"%#",op);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:MESSAGE_EN message:#"Unable to login. Please try again." delegate:self cancelButtonTitle:OK_EN otherButtonTitles:nil, nil];
[alert show];
NSLog(#"error.localizedDescription %#",error.localizedDescription);
}];
}
Note : Please do fill the fields with proper values and try.
dict is the Input postdata

I got this one from somewhere in SO question. See this:
- (IBAction)loginButtonPressed {
NSURL *baseURL = [NSURL URLWithString:#"http://myweb.mobile.com/WebServices/AppointmentService.asmx"];
//build normal NSMutableURLRequest objects
//make sure to setHTTPMethod to "POST".
//from https://github.com/AFNetworking/AFNetworking
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:baseURL];
[httpClient defaultValueForHeader:#"Accept"];
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
[usernameTextField text], kUsernameField,
[passwordTextField text], kPasswordField,
nil];
NSMutableURLRequest *request = [httpClient requestWithMethod:#"POST"
path:#"http://myweb.mobile.com/WebServices/AppointmentService.asmx/GetValidUser" parameters:params];
//Add your request object to an AFHTTPRequestOperation
AFHTTPRequestOperation *operation = [[[AFHTTPRequestOperation alloc]
initWithRequest:request] autorelease];
//"Why don't I get JSON / XML / Property List in my HTTP client callbacks?"
//see: https://github.com/AFNetworking/AFNetworking/wiki/AFNetworking-FAQ
//mattt's suggestion http://stackoverflow.com/a/9931815/1004227 -
//-still didn't prevent me from receiving plist data
//[httpClient registerHTTPOperationClass:
// [AFPropertyListParameterEncoding class]];
[httpClient registerHTTPOperationClass:[AFHTTPRequestOperation class]];
[operation setCompletionBlockWithSuccess:
^(AFHTTPRequestOperation *operation,
id responseObject) {
NSString *response = [operation responseString];
NSLog(#"response: [%#]",response);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"error: %#", [operation error]);
}];
//call start on your request operation
[operation start];
[httpClient release];
}
Hope this helps .. :)
EDIT
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager POST:URLString parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFormData:[email dataUsingEncoding:NSUTF8StringEncoding]
name:#"email"];
[formData appendPartWithFormData:[pass dataUsingEncoding:NSUTF8StringEncoding]
name:#"password"];
// etc.
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Response: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];

Use below code
NSDictionary *paramDictionary = [NSDictionary dictionaryWithObjectsAndKeys:#"first_Object",#"first_Key",#"second_Object",#"second_Key" nil];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager POST:#"YOUR_URL_STRING" parameters:paramDictionary success:^(AFHTTPRequestOperation *operation, id responseObject) {Success responce} failure:^(AFHTTPRequestOperation *operation, NSError *error) {failure responce}];
if you want you can set
manager.responseSerializer = [AFJSONResponseSerializer serializer];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
manager.securityPolicy.allowInvalidCertificates = YES;

Related

AFNetworking POST method call

I am new to AFNetworking. How can i execute the success and failure blocks of the following
NSMutableDictionary *rus = [[NSMutableDictionary alloc] init];
[rus setValue:#"1211" forKey:#"id"];
[rus setValue:#"33" forKey:#"man"];
[[AFHTTPRequestSerializer serializer] requestWithMethod:#"POST" URLString:#"http://mysite.co/service.php" rus];
How to show the success or failure after executing the above code fragment.
requestWithMethod does not actually complete the call, it just returns you an NSMutableURLRequest. You need to take that request and make an AFHTTPRequestOperation. You can set a success/failure block on this object and then run the start method.
NSMutableDictionary *rus = [[NSMutableDictionary alloc] init];
[rus setValue:#"1211" forKey:#"id"];
[rus setValue:#"33" forKey:#"man"];
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] requestWithMethod:#"POST" URLString:#"http://mysite.co/service.php" parameters:rus];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
// Code for success
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//Code for failure
}];
[operation start];
All that being said, are you using an outdated version of AFNetworking? The method you're referencing is deprecated.
- (NSMutableURLRequest *)requestWithMethod:(NSString *)method
URLString:(NSString *)URLString
parameters:(id)parameters
error:(NSError *__autoreleasing *)error
Above is the correct method to use. You should pass in an error object.
Finally, an even easier way to accomplish what you're doing with AFNetworking 2.0 is below:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager POST:#"http://mysite.co/service.php" parameters:rus success:^(AFHTTPRequestOperation *operation, id responseObject) {
// Code for success
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// Code for failure
}];
Try this code:
NSMutableDictionary *rus = [[NSMutableDictionary alloc] init];
[rus setValue:#"1211" forKey:#"id"];
[rus setValue:#"33" forKey:#"man"];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager POST:#"http://mysite.co/service.php" parameters:rus success:^(AFHTTPRequestOperation *operation, id responseObject) {
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
}];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager POST:#"http://mysite.co/service.php" parameters:rus success:^(AFHTTPRequestOperation *operation, id responseObject) {
// Code for success
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// Code for failure
}];
github's AFNetworking document
https://github.com/AFNetworking/AFNetworking

How to migrate AFHTTPClient, Afnetworking 1.0 to 2.0

My problem is that I have a old code and I dont know how to change it.
I had 1 class called API (AFHTTPClient) I have problems with 2 methods because I dont know how to put them in 2.0:
This:
-(void)commandWithParams:(NSMutableDictionary*)params onCompletion:(JSONResponseBlock)completionBlock
{
NSMutableURLRequest *apiRequest =
[self multipartFormRequestWithMethod:#"POST"
path:kAPIPath
parameters:params
constructingBodyWithBlock: ^(id formData) {
//TODO: attach file if needed
}];
AFJSONRequestOperation* operation = [[AFJSONRequestOperation alloc] initWithRequest: apiRequest];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
//success!
completionBlock(responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//failure :(
completionBlock([NSDictionary dictionaryWithObject:[error localizedDescription] forKey:#"error"]);
}];
[operation start];
}
and this:
#pragma mark - init
//intialize the API class with the destination host name
-(API*)init
{
//call super init
self = [super init];
if (self != nil) {
//initialize the object
user = nil;
[self registerHTTPOperationClass:[AFJSONRequestOperation class]];
// Accept HTTP Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1
[self setDefaultHeader:#"Accept" value:#"application/json"];
}
return self;
}
I do a new class called Api, now (AFHTTPRequestOperationManager) is good?
I try with this, but I dont have idea
-(API*)init
{//call super init
self = [super init];
//initialize the object
if (self != nil) {
//initialize the object
user = nil;
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
AFJSONRequestSerializer *a=[AFJSONRequestSerializer serializer];
[a setValue:#"Accept" forHTTPHeaderField:#"application/json"];
[a setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[a setValue:#"content-Type" forHTTPHeaderField:#"text/html"];
[a setValue : # "text / html; charset = UTF-8" forHTTPHeaderField : # "Content-Type" ];
}
return self;
}
-(void)commandWithParams:(NSMutableDictionary*)params onCompletion:(JSONResponseBlock)completionBlock
{
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = params;
NSURL *filePath = [NSURL URLWithString:#"http://162.243.199.147/mujeresquecorren/iReporter/index.php"];
[manager POST:#"api" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileURL:filePath name:#"api" error:nil];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Success: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
NSMutableURLRequest *apiRequest = [NSMutableURLRequest requestWithURL:filePath];
AFJSONRequestSerializer *requestSerializer = [AFJSONRequestSerializer serializer];
[requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Accept"];
// operationManagerInstance.requestSerializer = requestSerializer;
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]
initWithRequest:apiRequest];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager POST:#"http://162.243.199.147/mujeresquecorren/iReporter/index.php" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"%#", responseObject);
} failure:nil];
// AFJSONRequestOperation* operation = [[AFJSONRequestOperation alloc] initWithRequest: apiRequest];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
//success!
completionBlock(responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//failure :(
completionBlock([NSDictionary dictionaryWithObject:[error localizedDescription] forKey:#"error"]);
}];
[operation start];
}
and this is one of the errors:
rror: Error Domain=NSURLErrorDomain Code=-1002 "unsupported URL" UserInfo=0xa64f980 {NSErrorFailingURLStringKey=api, NSErrorFailingURLKey=api, NSLocalizedDescription=unsupported URL, NSUnderlyingError=0xa782e10 "unsupported URL"}
Please help, im going to be crazy with that and I need that my code works in my app!
Thanks a lot!!!!
It's all there in the error message. "api" isn't a valid URL. You need to either specify an absolute URL, or initialize your request operation manager with a baseURL, using initWithBaseURL:.

AFNetworking combine data and image to send to PHP

I am (finally) using afnetworking for my iOS project. I have managed with success to send POST data and an image to my php server, but in separated blocks of code.
Send Data:
NSDictionary *parameters = [NSDictionary dictionaryWithObjectsAndKeys:myname,#"name", mysencondname, #"twoname", nil];
NSURL *url = [NSURL URLWithString:#"http://DOMAIN.COM"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
[httpClient defaultValueForHeader:#"Accept"];
[httpClient postPath:#"post.php" parameters:parameters
success:^(AFHTTPRequestOperation *operation, id response) {
NSLog(#"operation hasAcceptableStatusCode: %d", [operation.response statusCode]);
[self requestDone:[operation.response statusCode]];
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error with request");
NSLog(#"%#",[error localizedDescription]);
[self requestFailed];
}];
Send Image:
NSData *imageToUpload = UIImagePNGRepresentation(_imageView.image);
AFHTTPClient *client= [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:#"http://www.DOMAIN.com"]];
NSMutableURLRequest *request = [client multipartFormRequestWithMethod:#"POST" path:#"upload.php" parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
[formData appendPartWithFileData: imageToUpload name:#"avatar" fileName:fullFilename mimeType:#"image/png"];
}];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *response = [operation responseString];
NSLog(#"response: [%#]",response);
[MBProgressHUD hideHUDForView:self.view animated:YES];
[self dismissViewControllerAnimated:YES completion:NULL];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
if([operation.response statusCode] == 403){
NSLog(#"Upload Failed");
[MBProgressHUD hideHUDForView:self.view animated:YES];
return;
}
NSLog(#"error: %#", [operation error]);
}];
My question is how can I combine them so I can send an image and some data like (myname, #"name", mysencondname, #"twoname") to my server with a single request ?
Inside the multipartFormRequestWithMethod method there is parameter called parameters that you can use to send some data along.
For example:
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
myName, #"name"
, secondName, #"twoname"
, nil];
NSMutableURLRequest *request = [client multipartFormRequestWithMethod:#"POST" path:#"upload.php" parameters:params constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
[formData appendPartWithFileData: imageToUpload name:#"avatar" fileName:fullFilename mimeType:#"image/png"];
}];

Upload image using AFnetworking did not response anything

Here's the problem :
I want to upload image immediately after finish choosing image from imagepicker.
So, I put my code to upload image using afnetworking in imagepicker delegate method.
But it doesn't response anything.
//set the imageview to current image after choosing
profilePic.image = image;
//dismiss the imagepicker
[picker dismissModalViewControllerAnimated:YES];
//start upload image code
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
#"steventi1901", #"username",
UIImagePNGRepresentation(profilePic.image), #"profile_pic",
nil];
AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:updateProfile];
NSData *imageToUpload = UIImagePNGRepresentation(profilePic.image);
NSMutableURLRequest *request = [client multipartFormRequestWithMethod:#"PUT" path:#"" parameters:params
constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
[formData appendPartWithFileData: imageToUpload name:#"file" fileName:#"temp.png" mimeType:#"image/png"];
//NSLog(#"dalem");
}];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *response = [operation responseString];
NSLog(#"response: [%#]",response);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
if([operation.response statusCode] == 403){
NSLog(#"Upload Failed");
return;
}
NSLog(#"error: %#", [operation error]);
}];
[operation start];
//end upload image code
It really didn't response anything so i didn't know if the process fail or success.
Best and Easy way to upload Image using Afnetworking.
Please use below AFNetworking.
pod 'AFNetworking', '~> 2.5.4'
//Create manager
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
//parameters if any
NSMutableDictionary *AddPost = [[NSMutableDictionary alloc]init];
[AddPost setValue:#"Addparma" forKey:#"param"];
NSString * url = [NSString stringWithFormat:#"www.addyourmainurl.com"];;
NSLog(#"AddPost %#",AddPost);
[manager POST:url parameters:[AddPost copy] constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
//add image data one by one
for(int i=0; i<[Array count];i++)
{
UIImage *eachImage = [Array objectAtIndex:i];
NSData *imageData = UIImageJPEGRepresentation(eachImage,0.5);
[formData appendPartWithFileData:imageData name:[NSString stringWithFormat:#"image%d",i] fileName:[NSString stringWithFormat:#"image%d.jpg",i ] mimeType:#"image/jpeg"];
}
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Success: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
have you set the delegate of the picker?
[yourPicker setDelegate:self]

AFNetworking Post Request

I'm a newbie in obj-c and have been using asihttp for some of my projects. When doing a post request in asihttp its done this way.
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:height forKey:#"user[height]"];
[request setPostValue:weight forKey:#"user[weight]"];
[request setDelegate:self];
[request startAsynchronous];
How would go about doing this is AFNetworking with a code example ?
I already got the get Json getrequest working in AFNetworking but this post request is giving me some problems. Thanks for help in advance.
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);
}];
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
height, #"user[height]",
weight, #"user[weight]",
nil];
AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:
[NSURL URLWithString:#"http://localhost:8080/"]];
[client postPath:#"/mypage.php" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *text = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(#"Response: %#", text);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"%#", [error localizedDescription]);
}];
Here is a simple AFNetworking POST I'm using. To get up and running after
reading the AFNetworking doc, wkiki, ref, etc, I learned a lot by
following http://nsscreencast.com/episodes/6-afnetworking and understanding
the associated code sample on github.
// Add this to the class you're working with - (id)init {}
_netInst = [MyApiClient sharedAFNetworkInstance];
// build the dictionary that AFNetworkng converts to a json object on the next line
// params = {"user":{"email":emailAddress,"password":password}};
NSDictionary *parameters =[NSDictionary dictionaryWithObjectsAndKeys:
userName, #"email", password, #"password", nil];
NSDictionary *params =[NSDictionary dictionaryWithObjectsAndKeys:
parameters, #"user", nil];
[_netInst postPath: #"users/login.json" parameters:params
success:^(AFHTTPRequestOperation *operation, id jsonResponse) {
NSLog (#"SUCCESS");
// jsonResponse = {"user":{"accessId":1234,"securityKey":"abc123"}};
_accessId = [jsonResponse valueForKeyPath:#"user.accessid"];
_securityKey = [jsonResponse valueForKeyPath:#"user.securitykey"];
return SUCCESS;
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"FAILED");
// handle failure
return error;
}
];
For AFNetworking 4
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
NSDictionary *params = #{#"user[height]": height,
#"user[weight]": weight};
[manager POST:#"https://example.com/myobject" parameters:params headers:nil progress:nil success:^(NSURLSessionTask *task, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(NSURLSessionTask *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
AFHTTPClient * Client = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:#"http://urlname"]];
NSDictionary * parameters = [[NSMutableDictionary alloc] init];
parameters = [NSDictionary dictionaryWithObjectsAndKeys:
height, #"user[height]",
weight, #"user[weight]",
nil];
[Client setParameterEncoding:AFJSONParameterEncoding];
[Client postPath:#"users/login.json" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"operation hasAcceptableStatusCode: %d", [operation.response statusCode]);
NSLog(#"response string: %# ", operation.responseString);
NSDictionary *jsonResponseDict = [operation.responseString JSONValue];
if ([[jsonResponseDict objectForKey:#"responseBody"] isKindOfClass:[NSMutableDictionary class]]) {
NSMutableDictionary *responseBody = [jsonResponseDict objectForKey:#"responseBody"];
//get the response here
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"error: %#", operation.responseString);
NSLog(#"%d",operation.response.statusCode);
}];
Hope this works.
Here an example with Swift 3.0
let manager = AFHTTPSessionManager(sessionConfiguration: URLSessionConfiguration.default)
manager.requestSerializer = AFJSONRequestSerializer()
manager.requestSerializer.setValue("application/json", forHTTPHeaderField: "Content-Type")
manager.requestSerializer.setValue("application/json", forHTTPHeaderField: "Accept")
if authenticated {
if let user = UserDAO.currentUser() {
manager.requestSerializer.setValue("Authorization", forHTTPHeaderField: user.headerForAuthentication())
}
}
manager.post(url, parameters: parameters, progress: nil, success: { (task: URLSessionDataTask, responseObject: Any?) in
if var jsonResponse = responseObject as? [String: AnyObject] {
// here read response
}
}) { (task: URLSessionDataTask?, error: Error) in
print("POST fails with error \(error)")
}
[SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeGradient];
[SVProgressHUD show];
NSDictionary *dictParam =#{#"user_id":#"31"};// Add perameter
NSString *URLString =#"your url string";
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager setResponseSerializer:[AFHTTPResponseSerializer serializer]];
[manager.requestSerializer setValue:strGlobalLoginToken forHTTPHeaderField:#"Authorization"];//strGlobalLoginToken is your login token
// [manager.requestSerializer setValue:setHeaderEnv forHTTPHeaderField:#"Env"];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:#"application/json", #"text/json", #"text/javascript",#"text/html",#"text/plain",#"application/rss+xml", nil];
[manager POST:URLString parameters:dictParam progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject)
{
NSDictionary *response = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
NSLog(#"Response DICT:%#",response);
if ([[[[response objectForKey:#"response"] objectAtIndex:0] objectForKey:#"status"] isEqualToString:#"true"])
{
for (NSMutableDictionary *dicAll in [[[response objectForKey:#"response"]objectAtIndex:0]objectForKey:#"plans"])
{
[yourNsmutableArray addObject:[dicAll mutableCopy]];
}
//yourNsmutableArray Nsmutablearray alloction in view didload
NSLog(#"yourNsmutableArray %#",yourNsmutableArray);
}
else
{
NSLog(#"False");
}
[SVProgressHUD dismiss];
} failure:^(NSURLSessionDataTask *_Nullable task, NSError *_Nonnull error)
{
NSLog(#"RESPONSE STRING:%#",task.response);
NSLog(#"error userInfo:%#",error.userInfo);
NSString *errResponse = [[NSString alloc] initWithData:(NSData *)error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] encoding:NSUTF8StringEncoding];
NSLog(#"URLString :--->> %# Error********* %#",URLString,errResponse);
[SVProgressHUD dismiss];
}];
For AFNetworking 3.0 and Swift. Maybe we can use like this:
let configutation = NSURLSessionConfiguration.defaultSessionConfiguration()
manager = AFHTTPSessionManager(sessionConfiguration: configutation)
let urlString = "url"
manager.POST(urlString, parameters: [params here], progress: nil, success: { (dataTask: NSURLSessionDataTask, response: AnyObject?) -> Void in
print(dataTask)
print(response)
}) { (dataTask: NSURLSessionDataTask?, error: NSError) -> Void in
print(error)
}
Hope this will help other find answer like me!
For AFNetworking 3.0 (iOS9 or greter)
NSString *strURL = #"https://exampleWeb.com/webserviceOBJ";
NSDictionary *dictParamiters = #{#"user[height]": height,#"user[weight]": weight};
NSString *aStrParams = [self getFormDataStringWithDictParams:dictParamiters];
NSData *aData = [aStrParams dataUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *aRequest = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:strURL]];
[aRequest setHTTPMethod:#"POST"];
[aRequest setHTTPBody:aData];
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:nil delegateQueue:nil];
[aRequest setHTTPBody:aData];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:aRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
//
if (error ==nil) {
NSString *aStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"ResponseString:%#",aStr);
NSMutableDictionary *aMutDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
dispatch_async(dispatch_get_main_queue(), ^{
completionBlock(aMutDict);
NSLog(#"responce:%#",aMutDict)
});
}
else
{
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(#"error:%#",error.locali)
});
}
}];
[postDataTask resume];
and Add
-(NSString *)getFormDataStringWithDictParams:(NSDictionary *)aDict
{
NSMutableString *aMutStr = [[NSMutableString alloc]initWithString:#""];
for (NSString *aKey in aDict.allKeys) {
[aMutStr appendFormat:#"%#=%#&",aKey,aDict[aKey]];
}
NSString *aStrParam;
if (aMutStr.length>2) {
aStrParam = [aMutStr substringWithRange:NSMakeRange(0, aMutStr.length-1)];
}
else
aStrParam = #"";
return aStrParam;
}
NSURL *URL = [NSURL URLWithString:#"url"];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
NSDictionary *params = #{#"prefix":#"param",#"prefix":#"param",#"prefix":#"param"};
[manager POST:URL.absoluteString parameters:params progress:nil success:^(NSURLSessionTask *task, id responseObject) {
self.arrayFromPost = [responseObject objectForKey:#"data"];
// values in foreach loop
NSLog(#"POst send: %#",_arrayFromPost);
} failure:^(NSURLSessionTask *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
NSMutableDictionary *dictParam = [NSMutableDictionary dictionary];
[dictParam setValue:#"VALUE_NAME" forKey:#"KEY_NAME"]; //set parameters like id, name, date, product_name etc
if ([[AppDelegate instance] checkInternetConnection]) {
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictParam options:NSJSONWritingPrettyPrinted error:&error];
if (jsonData) {
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"Api Url"]
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:30.0f];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:jsonData];
[request setValue:ACCESS_TOKEN forHTTPHeaderField:#"TOKEN"];
AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
op.responseSerializer = [AFJSONResponseSerializer serializer];
op.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:#"text/plain",#"text/html",#"application/json", nil];
[op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
arrayList = [responseObject valueForKey:#"data"];
[_tblView reloadData];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//show failure alert
}];
[op start];
}
} else {
[UIAlertView infoAlertWithMessage:NO_INTERNET_AVAIL andTitle:APP_NAME];
}
please try below answer.
+(void)callAFWSPost:(NSDictionary *)dict withURL:(NSString *)strUrl
withBlock:(dictionary)block
{
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc]initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[manager.requestSerializer setValue:#"application/x-www-form-urlencoded; charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:#"application/json", #"text/json", #"text/javascript",#"text/html", nil];
[manager POST:[NSString stringWithFormat:#"%#/%#",WebserviceUrl,strUrl] parameters:dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject)
{
if (!responseObject)
{
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setObject:ServerResponceError forKey:#"error"];
block(responseObject);
return ;
}
else if ([responseObject isKindOfClass:[NSDictionary class]]) {
block(responseObject);
return ;
}
}
failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error)
{
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setObject:ServerResponceError forKey:#"error"];
block(dict);
}];
}
for login screen;
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
dict = [NSMutableDictionary
dictionaryWithObjectsAndKeys:_usernametf.text, #"username",_passwordtf.text, #"password", nil];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
[manager POST:#"enter your url" parameters:dict progress:nil success:^(NSURLSessionTask *task, id responseObject) {
NSLog(#"%#", responseObject);
}
failure:^(NSURLSessionTask *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
}
// For Image with parameter /// AFMultipartFormData
NSDictionary *dictParam =#{#"user_id":strGlobalUserId,#"name":[dictParameter objectForKey:#"Name"],#"contact":[dictParameter objectForKey:#"Contact Number"]};
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:webServiceUrl]];
[manager.requestSerializer setValue:strGlobalLoginToken forHTTPHeaderField:#"Authorization"];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:#"application/json", #"text/json", #"text/javascript",#"text/html",#"text/plain",#"application/rss+xml", nil];
[manager POST:#"update_profile" parameters:dictParam constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
if (Imagedata.length>0) {
[formData appendPartWithFileData:Imagedata name:#"profile_pic" fileName:#"photo.jpg" mimeType:#"image/jpeg"];
}
} progress:nil
success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject)
{
NSLog(#"update_profile %#", responseObject);
if ([[[[responseObject objectForKey:#"response"] objectAtIndex:0] objectForKey:#"status"] isEqualToString:#"true"])
{
[self presentViewController:[global SimpleAlertviewcontroller:#"" Body:[[[responseObject objectForKey:#"response"] objectAtIndex:0] objectForKey:#"response_msg"] handler:^(UIAlertAction *action) {
[self.navigationController popViewControllerAnimated:YES];
}] animated:YES completion:nil];
}
else
{
[self presentViewController:[global SimpleAlertviewcontroller:#"" Body:[[[responseObject objectForKey:#"response"] objectAtIndex:0] objectForKey:#"response_msg"] handler:^(UIAlertAction *action) {
}] animated:YES completion:nil];
}
[SVProgressHUD dismiss];
} failure:^(NSURLSessionDataTask *_Nullable task, NSError *_Nonnull error)
{
[SVProgressHUD dismiss];
}];
Using AFNetworking 3.0, you should write:
NSString *strURL = #"https://exampleWeb.com/webserviceOBJ";
NSURL * urlStr = [NSURL URLWithString:strURL];
NSDictionary *dictParameters = #{#"user[height]": height,#"user[weight]": weight};
AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];
[manager POST:url.absoluteString parameters:dictParameters success:^(NSURLSessionTask *task, id responseObject) {
NSLog(#"PLIST: %#", responseObject);
} failure:^(NSURLSessionTask *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];

Resources