how to communicate with server with afnetworking? - ios

I am using AFNetworking Please take a look at my code
+(void)requestLogin:(id<LoginRequestDelegate>) delegate LoginURL:(NSString *)loginurl{
static User *user;
static id <LoginRequestDelegate> del;
del=delegate;
static AFHTTPRequestOperation *afRequest;
if(afRequest){
return;
}
isLogin = NO;
Reachability *objInternetReachable = [Reachability reachabilityForInternetConnection];
NetworkStatus status = [objInternetReachable currentReachabilityStatus];
if(status != NotReachable) {
NSString *strUrl=loginurl;
NSLog(#"Login JSON URL %#", strUrl);
strUrl=[strUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURLRequest *urlReq=[[NSURLRequest alloc] initWithURL:[NSURL URLWithString:strUrl] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
afRequest=[[AFHTTPRequestOperation alloc] initWithRequest:urlReq];
AFNetworkActivityIndicatorManager * newactivity = [[AFNetworkActivityIndicatorManager alloc] init];
newactivity.enabled = YES;
[afRequest setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
newactivity.enabled = NO;
NSString *strRes=[[NSString alloc] initWithData:responseObject encoding:NSASCIIStringEncoding];
//JSON DATA
NSDictionary *dic=[[NSDictionary alloc]init];
SBJsonParser *parser=[[SBJsonParser alloc] init];
dic=[parser objectWithString:strRes];
NSLog(#"Dic :- %#", dic);
if(dic){
NSString *isLoginRes = [dic objectForKey:#"login"];
if([isLoginRes isEqualToString:#"true"]){
NSLog(#"login res %#",isLoginRes);
isLogin = YES;
NSDictionary *resp = [dic objectForKey:#"resp"];
user = [User sharedInstance];
// User
NSDictionary *userDic = [resp objectForKey:#"User"];
user.userId = [userDic objectForKey:#"id"];
user.userEmail = [userDic objectForKey:#"email"];
I am using this piece of code, but when i reach on this method it jump to failure block.
[afRequest setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
This block is not executed.
The program moves jump on this block
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
newactivity.enabled = NO;
if(del){
[del isLoginRespomce:isLogin LoginDetail:user];
}

Your code could be much simpler, use for the AFNetworking stuff the AFHTTPRequestOperationManager, it's really easy to use and works just as good as allocating your own AFHTTPRequestOperation etc.
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:loginurl parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];

Related

How to call an OAuth 2.0 API from iOS

I am working on Fitbit integration. How can I make request and authorize its OAuth 2.0 API. I checked ASIHTTPRequest but it is not available on ARC. Can I do it with AFNetworking ? I am using Objective-C.
Its done using AFNetworking using AFOAuth2Manager here is the code
In ViewController.m
#define CLIENT_ID #"your client id"
#define CONSUMER_SECRET #"your consumer secret"
Start authorization using safari.
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:#"https://www.fitbit.com/oauth2/authorize?response_type=code&client_id=227FKJ&redirect_uri=http%3A%2F%2Fcallback.com%2Ffitbit&scope=activity%20nutrition%20heartrate%20location%20nutrition%20profile%20settings%20sleep%20social%20weight"]];
get response code from NSUserDefaults
NSString *string = [[NSUserDefaults standardUserDefaults] valueForKey:#"auth_code"];
NSURL *baseURL = [NSURL URLWithString:#"https://www.fitbit.com/oauth2/authorize"];
AFOAuth2Manager *OAuth2Manager =
[[AFOAuth2Manager alloc] initWithBaseURL:baseURL
clientID:CLIENT_ID secret:CONSUMER_SECRET];
NSDictionary *dict = #{#"client_id":CLIENT_ID, #"grant_type":#"authorization_code",#"redirect_uri":#"http://lampdemos.com/fitbit",#"code":string};
[OAuth2Manager authenticateUsingOAuthWithURLString:#"https://api.fitbit.com/oauth2/token" parameters:dict success:^(AFOAuthCredential *credential) {
NSLog(#"Token: %#", credential.accessToken);
AppDelegate *adddel = (AppDelegate *)[[UIApplication sharedApplication]delegate];
adddel.credential = credential;
[self getUserProfileWithCredentials:credential];
} failure:^(NSError *error) {
NSLog(#"Error: %#", error);
}];
call further requests
-(void)getUserProfileWithCredentials:(AFOAuthCredential*)credential{
NSURL *baseURL = [NSURL URLWithString:#"https://www.fitbit.com/oauth2/authorize"];
AFHTTPRequestOperationManager *manager =
[[AFHTTPRequestOperationManager alloc] initWithBaseURL:baseURL];
[manager.requestSerializer setAuthorizationHeaderFieldWithCredential:credential];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager GET:#"https://api.fitbit.com/1/user/-/profile.json"
parameters:nil
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSDictionary *dictResponse = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
NSDictionary *userDict =[dictResponse valueForKey:#"user"];
NSLog(#"Success: %#", userDict);
NSMutableString *str =[NSMutableString stringWithFormat:#"%#",#""];
for (NSString *key in [userDict allKeys]) {
[str appendFormat:#"%# %#\n",key,[NSString stringWithFormat:#"%#",[userDict valueForKey:key]]];
}
self.profileDetails.text =str;
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Failure: %#", error);
}];
}

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 2.0 update on an existing project

I recently updated my project to 2.0 of AFNetworking and it appears that the AFHTTPClient file is missing.
I read the following at: https://github.com/AFNetworking/AFNetworking/wiki/AFNetworking-2.0-Migration-Guide
It appears i will now have to use AFHTTPRequestOperation ?
If so how can I modify the following piece of code to the new AFHTTPRequestOperation?
NSURL *url = [NSURL URLWithString:WEB_SERVICE_BASE_URL];
AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:url];
[client registerHTTPOperationClass:[AFJSONRequestOperation class]];
[client setDefaultHeader:#"Accept" value:#"application/json"];
[client postPath:LOGIN_PATH parameters:[NSDictionary dictionaryWithObjectsAndKeys:self.userNameOrEmail.text ,#"userNameOrEmail",self.password.text,#"password", nil]
success:^(AFHTTPRequestOperation *operation, id responseObject)
{
bool success = [[responseObject valueForKeyPath:#"success"] boolValue];
NSString *displayMessage = [responseObject valueForKeyPath:#"displaymessage"];
if (success) {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:self.userNameOrEmail.text forKey:#"userNameOrEmail"];
[defaults setObject:self.password.text forKey:#"password"];
// [Flurry setUserID:self.userNameOrEmail.text];
[SVProgressHUD showSuccessWithStatus:displayMessage];
[self dismissViewControllerAnimated:YES completion:nil];
} else {
[SVProgressHUD showErrorWithStatus:displayMessage];
}
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
NSLog(#"error is: %#", error);
[SVProgressHUD showErrorWithStatus:MSG_SERVER_ERROR];
}];
UPDATE: I did the following:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = [NSDictionary dictionaryWithObjectsAndKeys:self.userName.text ,#"user", self.email.text, #"email",self.password.text,#"password", nil];
[manager POST:WEB_SERVICE_BASE_URL parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
bool success = [[responseObject valueForKeyPath:#"success"] boolValue]? #"YES" : #"NO";
NSString *displayMessage = [responseObject valueForKeyPath:#"displaymessage"];
if (success) {
[SVProgressHUD showSuccessWithStatus:displayMessage];
[self.navigationController popToRootViewControllerAnimated:YES];
} else {
[SVProgressHUD showErrorWithStatus:displayMessage];
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
[SVProgressHUD showErrorWithStatus:MSG_SERVER_ERROR];
}];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = [NSDictionary dictionaryWithObjectsAndKeys:self.userName.text ,#"user", self.email.text, #"email",self.password.text,#"password", nil];
[manager POST:WEB_SERVICE_BASE_URL parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
bool success = [[responseObject valueForKeyPath:#"success"] boolValue]? #"YES" : #"NO";
NSString *displayMessage = [responseObject valueForKeyPath:#"displaymessage"];
if (success) {
[SVProgressHUD showSuccessWithStatus:displayMessage];
[self.navigationController popToRootViewControllerAnimated:YES];
} else {
[SVProgressHUD showErrorWithStatus:displayMessage];
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
[SVProgressHUD showErrorWithStatus:MSG_SERVER_ERROR];
}];

iOS - Increase timeout for AFHTTPRequestOperationManager

I'm downloading JSON data from a very slow server. It takes about a minute to get a resoonse from the server. I use AFNetworking library and my code throws "The request timed out" error:
NSString *urlString = [NSString stringWithFormat:#"%#/account.do?JSON&sysparm_action=getRecords",baseUrlString];
NSString *login = [[NSUserDefaults standardUserDefaults] objectForKey:#"login"];
NSString *password = [[NSUserDefaults standardUserDefaults] objectForKey:#"password"];
[manager setRequestSerializer:[AFHTTPRequestSerializer serializer]];
[manager.requestSerializer setAuthorizationHeaderFieldWithUsername:login password:password];
[manager GET:urlString parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
[self parseJsonWithAccountsData:responseObject];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", operation.responseString);
[self performSelectorOnMainThread:#selector(failedWithContactsDownload) withObject:nil waitUntilDone:YES];
}];
Didn't find a way to set a timeout for AFHTTPRequestOperationManager. How can I do it?
In AFNetworking 2 library there is method in AFHTTPRequestSerializer set the request time out interval directly.
NSString *urlString = [NSString stringWithFormat:#"%#/account.do?JSON&sysparm_action=getRecords",baseUrlString];
NSString *login = [[NSUserDefaults standardUserDefaults] objectForKey:#"login"];
NSString *password = [[NSUserDefaults standardUserDefaults] objectForKey:#"password"];
[manager setRequestSerializer:[AFHTTPRequestSerializer serializer]];
[manager.requestSerializer setAuthorizationHeaderFieldWithUsername:login password:password];
[manager.requestSerializer setTimeoutInterval:TIME_OUT_INTERVAL];
[manager GET:urlString parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
[self parseJsonWithAccountsData:responseObject];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", operation.responseString);
[self performSelectorOnMainThread:#selector(failedWithContactsDownload) withObject:nil waitUntilDone:YES];
}];
You don't need to override the class to set the request time out interval.
Method 1.
I think the best way is to subclass AFHTTPRequestSerializer and override
- (NSMutableURLRequest *)requestWithMethod:(NSString *)method
URLString:(NSString *)URLString
parameters:(NSDictionary *)parameters
like this:
- (NSMutableURLRequest *)requestWithMethod:(NSString *)method
URLString:(NSString *)URLString
parameters:(NSDictionary *)parameters
{
NSMutableURLRequest *request = [super requestWithMethod:method URLString:URLString parameters:parameters];
[request setTimeoutInterval:YOUR_TIMEOUT_INTERVAL_HERE];
return request;
}
and then
NSString *urlString = [NSString stringWithFormat:#"%#/account.do?JSON&sysparm_action=getRecords",baseUrlString];
NSString *login = [[NSUserDefaults standardUserDefaults] objectForKey:#"login"];
NSString *password = [[NSUserDefaults standardUserDefaults] objectForKey:#"password"];
[manager setRequestSerializer:YOUR_NEW_REQUEST_SERIALIZER_HERE];
[manager.requestSerializer setAuthorizationHeaderFieldWithUsername:login password:password];
[manager GET:urlString parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
[self parseJsonWithAccountsData:responseObject];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", operation.responseString);
[self performSelectorOnMainThread:#selector(failedWithContactsDownload) withObject:nil waitUntilDone:YES];
}];
Method 2
NSString *urlString = [NSString stringWithFormat:#"%#/account.do?JSON&sysparm_action=getRecords",baseUrlString];
NSString *login = [[NSUserDefaults standardUserDefaults] objectForKey:#"login"];
NSString *password = [[NSUserDefaults standardUserDefaults] objectForKey:#"password"];
[manager setRequestSerializer:[AFHTTPRequestSerializer serializer]];
[manager.requestSerializer setAuthorizationHeaderFieldWithUsername:login password:password];
NSMutableURLRequest *request = [manager.requestSerializer requestWithMethod:#"GET" URLString:[[NSURL URLWithString:urlString relativeToURL:manager.baseURL] absoluteString] parameters:nil];
[request setTimeoutInterval:YOUR_TIMEOUT_INTERVAL_HERE];
AFHTTPRequestOperation *operation = [manager HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
[self parseJsonWithAccountsData:responseObject];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", operation.responseString);
[self performSelectorOnMainThread:#selector(failedWithContactsDownload) withObject:nil waitUntilDone:YES];
}];
[manager.operationQueue addOperation:operation];
I'm a bit lazy to categorize or subclass. You can access the manager's request serializer directly:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer.timeoutInterval = INTERNET_TIMEOUT;
manager.requestSerializer.cachePolicy = NSURLRequestReloadIgnoringLocalAndRemoteCacheData;
Create a subclass
self.requestOperationManager.requestSerializer = [[TimeoutAFHTTPRequestSerializer alloc] initWithTimeout:30];
TimeoutAFHTTPRequestSerializer.h
#import "AFURLRequestSerialization.h"
#interface TimeoutAFHTTPRequestSerializer : AFHTTPRequestSerializer
#property (nonatomic, assign) NSTimeInterval timeout;
- (id)initWithTimeout:(NSTimeInterval)timeout;
#end
TimeoutAFHTTPRequestSerializer.m
#import "TimeoutAFHTTPRequestSerializer.h"
#implementation TimeoutAFHTTPRequestSerializer
- (id)initWithTimeout:(NSTimeInterval)timeout {
self = [super init];
if (self) {
self.timeout = timeout;
}
return self;
}
- (NSMutableURLRequest *)requestWithMethod:(NSString *)method
URLString:(NSString *)URLString
parameters:(NSDictionary *)parameters
error:(NSError *__autoreleasing *)error
{
NSMutableURLRequest *request = [super requestWithMethod:method URLString:URLString parameters:parameters error:error];
if (self.timeout > 0) {
[request setTimeoutInterval:self.timeout];
}
return request;
}
#end
Actually, the value of timeoutInterval property is ignored - I've checked by debugging the method requestWithMethod:URLString:parameters:error:
I managed to subclass and override the method (Swift)
class RequestSerializer: AFHTTPRequestSerializer {
override func requestWithMethod(method: String!, URLString: String!, parameters:AnyObject!, error: NSErrorPointer) -> NSMutableURLRequest {
var req = super.requestWithMethod(method, URLString: URLString, parameters: parameters, error: error)
req.timeoutInterval = self.timeoutInterval
return req
}
}

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