Sending array of dictionary with afnetworking 2.0 - ios

I've a big problem, I'm trying to send an array of dictionary with afnetworking, that's my code:
checkDeliveryParams = #{#"cart_total":#(cart_total),#"shipping":#{#"address":[User sharedInstance].shipping_city,#"country":#"IT",#"postcode":[User sharedInstance].shipping_postcode,#"state":[User sharedInstance].shipping_provincia},#"user_id":#([User sharedInstance].user_id),#"cart_contents":temp};
cart total it's an array like this
(
quantity:1
product_id:2
)
but server receive something like this
(
quantity:1
),
(
product_id:2
)
my request code is
+(void)GET:(NSString *)path
params:(NSDictionary *)params
auth:(BOOL)authenticate
success:(void (^)(NSDictionary* responseObject))success
failure:(void (^)(NSError *error, NSDictionary* responseObject))failure{
NSString *URLString = [#"" stringByAppendingPathComponent:path];
NSLog(#"GET - API URL: %#", URLString);
AFHTTPRequestOperationManager *manager = [Rest commonManager:path sendAuthToken:authenticate];
// manager.requestSerializer=NSJSONSerialization ;
[manager GET:URLString parameters:params success:^(AFHTTPRequestOperation *operation, NSDictionary *responsedata){
NSLog(#"ok della richiesta %#",responsedata);
[Rest verbose:responsedata];
success(responsedata);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"errore della richiesta %#",error.localizedDescription);
failure(error,[Rest parseErrorResponseForOperation:operation]);
}];
}
I've tried a lot of method, I've tried to set nsjonserializer, "application/json", I've already tried to use NSURLSessionDataTask...
Sorry for my English, someone can help me ?
the common manager call in [rest commonManager] is defined in this method
+(AFHTTPRequestOperationManager *)commonManager:(NSString *)path sendAuthToken:(BOOL)sendToken{
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments];
manager.securityPolicy.allowInvalidCertificates = NO;
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager.requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[manager.requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Accept"];
if([Session isOpen] && [Rest authorizationRequiredForPath:path] && sendToken){
[manager.requestSerializer setValue:[NSString stringWithFormat:#"Bearer %#", [Session token]] forHTTPHeaderField:#"Authorization"];
}
return manager;
}

that's how I send parameters in get call
+(void)GET:(NSString *)path
params:(NSDictionary *)params
auth:(BOOL)authenticate
success:(void (^)(NSDictionary* responseObject))success
failure:(void (^)(NSError *error, NSDictionary* responseObject))failure{
NSString *URLString = [#"" stringByAppendingPathComponent:path];
NSLog(#"GET - API URL: %#", URLString);
AFHTTPRequestOperationManager *manager = [Rest commonManager:path sendAuthToken:authenticate];
// manager.requestSerializer=NSJSONSerialization ;
[manager GET:URLString parameters:params success:^(AFHTTPRequestOperation *operation, NSDictionary *responsedata){
NSLog(#"ok della richiesta %#",responsedata);
[Rest verbose:responsedata];
success(responsedata);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"errore della richiesta %#",error.localizedDescription);
failure(error,[Rest parseErrorResponseForOperation:operation]);
}];
}

Related

AFNetworking calling curl command to get access token

I a curl command to get the access token, which looks below command -
curl --data 'client_id=XXX&grant_type=XXX&client_secret=XXX&scope=XXX' "https://abc-internal.XXX.com/as/resourceOwner" -k -i
I need to call this command from my objective C code to get the access token, here is my code which is not working -
NSURL *strURL = [NSURL URLWithString:#"https://abc-internal.XXX.com/as/resourceOwner"];
NSString *icpStr = [strURL absoluteString];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager.requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[manager.requestSerializer setValue:#"XXX" forHTTPHeaderField:#"client_id"];
[manager.requestSerializer setValue:#"XXX" forHTTPHeaderField:#"grant_type"];
[manager.requestSerializer setValue:#"XXX" forHTTPHeaderField:#"client_secret"];
[manager.requestSerializer setValue:#"XXX" forHTTPHeaderField:#"scope"];
AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
[securityPolicy setValidatesDomainName:NO];
[securityPolicy setAllowInvalidCertificates:YES];
manager.securityPolicy = securityPolicy;
[manager GET:icpStr parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
if ([responseObject isKindOfClass:[NSData class]])
{
NSError *parseError = nil;
NSDictionary *resultsDictionary = (NSDictionary *) [NSJSONSerialization JSONObjectWithData: responseObject options: 0 error: &parseError];
if (parseError)
{
NSLog(#"Parse Error %#",parseError);
}else{
NSLog(#"Results %#",resultsDictionary);
}
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error %#",error.localizedDescription);
}];
And i get error saying its bad request -
Error Domain=com.alamofire.error.serialization.response Code=-1011 "Request failed: bad request (400)"
Any suggestion would be much appreciated. I am new to objective c coding so i would really appreciate if someone can help me here.
NSString *URLString = #"https://abc-internal.XXX.com/as/resourceOwner";
AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];
manager.responseSerializer =[AFHTTPResponseSerializer serializer];
[manager GET:URLString parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
if ([responseObject isKindOfClass:[NSData class]]) {
NSError *parseError = nil;
NSDictionary *resultsDictionary = (NSDictionary *) [NSJSONSerialization JSONObjectWithData: responseObject options: 0 error: &parseError];
if (parseError)
{
NSLog(#"Parse Error %#",parseError);
}else{
NSLog(#"Results %#",resultsDictionary);
}
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
}];

How to convert JSON serialized data to NSDictionary in Objective C?

I Have Used the following method to convert data to dictionary in my App but it shows json object was nil.
It's printing "jsonObject is null".
Is there any problem with "error:nil".
- (void)postNonceToServer:(NSString *)paymentMethodNonce {
// Update URL with your server
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:#"text/html"];
NSDictionary *parameters = #{#"payment_method_nonce":paymentMethodNonce,#"amount":amountStr,#"tripid":tripIdStr,#"currencycode":currencyStr};
[manager POST:#"http:url.php" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
//NSArray *response = responseObject;
//response = responseObject;
NSLog(#"responseObject is %#",responseObject);
jsonObject=[NSJSONSerialization
JSONObjectWithData:responseObject
options:NSJSONReadingMutableLeaves
error:nil];
NSLog(#"jsonObject is %#",jsonObject);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
}
Here, I am using AFNetworking 3.0. So i will give you "POST" method code in AFNetworking 3.0 version.
Step 1 :- Create one NSObject Class and write down this method in .h file.
+ (void)requestPostUrl: (NSString *)serviceName parameters:(NSDictionary *)dictParams success:(void (^)(NSDictionary *responce))success failure:(void (^)(NSError *error))failure;
Step 2 :- Write down this code in .m file
here "kBaseURL" means Web service URL and "serviceName" name of service.
+ (void)requestPostUrl: (NSString *)serviceName parameters:(NSDictionary *)dictParams success:(void (^)(NSDictionary *responce))success failure:(void (^)(NSError *error))failure {
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager.requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[manager.requestSerializer setQueryStringSerializationWithBlock:^NSString * _Nonnull(NSURLRequest * _Nonnull request, id _Nonnull parameters, NSError * _Nullable __autoreleasing * _Nullable error) {
//Here your data converting in JSON.
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters options:NSJSONWritingPrettyPrinted error:error];
NSString *argString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
return argString;
}];
NSString *strService = [NSString stringWithFormat:#"%#%#",kBaseURL,serviceName];
[manager setResponseSerializer:[AFHTTPResponseSerializer serializer]];
//[SVProgressHUD showWithStatus:#"Please wait..."];
[SVProgressHUD show];
[manager POST:strService parameters:dictParams progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
if([responseObject isKindOfClass:[NSDictionary class]]) {
if(success) {
[SVProgressHUD dismiss];
success(responseObject);
}
}
else
{
NSDictionary *response = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
if(success) {
[SVProgressHUD dismiss];
NSLog(#"POST Response : %#",response);
success(response);
}
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
if(failure) {
[SVProgressHUD dismiss];
failure(error);
}
}];
}

afnetworking 3.0 Migration: how to POST with headers and HTTP Body

I am trying to make a POST request which has HTTPHeader Fields and a HTTP body to the youtube API.
Previously in version 2.0 of AFNetworking, I used to do it this way which worked:
NSDictionary *parameters = #{#"snippet": #{#"textOriginal":self.commentToPost.text,#"parentId":self.commentReplyingTo.commentId}};
NSString *url = [NSString stringWithFormat:#"https://www.googleapis.com/youtube/v3/comments?part=snippet&access_token=%#",[[LoginSingleton sharedInstance] getaccesstoken]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters
options:0
error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
// And finally, add it to HTTP body and job done.
[request setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer.timeoutInterval=[[[NSUserDefaults standardUserDefaults] valueForKey:#"timeoutInterval"] longValue];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
AFHTTPRequestOperation *operation = [manager HTTPRequestOperationWithRequest:request progress:nil success:^(NSURLSessionTask *task, id responseObject) {
NSLog(#"Reply JSON: %#", responseObject);
}
} failure:^(NSURLSessionTask *operation, NSError *error) {
NSLog(#"Error: %#, %#, %#, %#, %#", error, operation.responseObject, operation.responseData, operation.responseString, operation.request);
}];
[operation start];
The migration docs for version 3.0 replaces AFHTTPRequestOperationManager with AFHTTPSessionManager
However I can't seem to find a HTTPRequestOperationWithRequest method for the AFHTTPSessionManager.
I tried using the constructingBodyWithBlock but it doesn't work maybe because I am not doing it correctly.
This is what I have so far which doesn't work:
NSDictionary *body = #{#"snippet": #{#"topLevelComment":#{#"snippet":#{#"textOriginal":self.commentToPost.text}},#"videoId":self.videoIdPostingOn}};
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:body
options:0
error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
AFJSONRequestSerializer *serializer = [AFJSONRequestSerializer serializer];
serializer.timeoutInterval= [[[NSUserDefaults standardUserDefaults] valueForKey:#"timeoutInterval"] longValue];
[serializer setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[serializer setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[manager POST:[NSString stringWithFormat:#"https://www.googleapis.com/youtube/v3/commentThreads?part=snippet&access_token=%#",[[LoginSingleton sharedInstance] getaccesstoken]] parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
[formData appendPartWithHeaders:nil body:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(#"Reply JSON: %#", responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(#"Error: %#, %#, %#, %#, %#", error, operation.responseObject, operation.responseData, operation.responseString, operation.request);
}];
Another way to call a POST method with AFNetworking 3.0 is:
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc]initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager.requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[manager POST:url parameters:parametersDictionary progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(#"success!");
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(#"error: %#", error);
}];
Hope it helps!
I was able to figure this out myself.
Here's the solution.
First, you need to create the NSMutableURLRequest from AFJSONRequestSerializer first where you can set the method type to POST.
On this request, you get to setHTTPBody after you have set your HTTPHeaderFields. Make sure to set the body after you have set the Header fields for content-type, or else the api will give a 400 error.
Then on the manager create a dataTaskWithRequest using the above NSMutableURLRequest. Don't forget to resume the dataTask at the very end or else nothing will get sent yet. Here's my solution code, hopefully someone gets to use this successfully:
NSDictionary *body = #{#"snippet": #{#"topLevelComment":#{#"snippet":#{#"textOriginal":self.commentToPost.text}},#"videoId":self.videoIdPostingOn}};
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:body options:0 error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSMutableURLRequest *req = [[AFJSONRequestSerializer serializer] requestWithMethod:#"POST" URLString:[NSString stringWithFormat:#"https://www.googleapis.com/youtube/v3/commentThreads?part=snippet&access_token=%#",[[LoginSingleton sharedInstance] getaccesstoken]] parameters:nil error:nil];
req.timeoutInterval= [[[NSUserDefaults standardUserDefaults] valueForKey:#"timeoutInterval"] longValue];
[req setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[req setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[req setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
[[manager dataTaskWithRequest:req completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (!error) {
NSLog(#"Reply JSON: %#", responseObject);
if ([responseObject isKindOfClass:[NSDictionary class]]) {
//blah blah
}
} else {
NSLog(#"Error: %#, %#, %#", error, response, responseObject);
}
}] resume];
Accepted answer of #Pranoy C is converted for AFNetworking 3.0
NSError *writeError = nil;
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:params options:NSJSONWritingPrettyPrinted error:&writeError];
NSString* jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:120];
[request setHTTPMethod:#"POST"];
[request setValue: #"application/json; encoding=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setValue: #"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPBody: [jsonString dataUsingEncoding:NSUTF8StringEncoding]];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[manager dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (!error) {
NSLog(#"Reply JSON: %#", responseObject);
if ([responseObject isKindOfClass:[NSDictionary class]]) {
//blah blah
}
} else {
NSLog(#"Error: %#", error);
NSLog(#"Response: %#",response);
NSLog(#"Response Object: %#",responseObject);
}
}] resume];
For HTTPBody with JSON
[sessionManager.requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[sessionManager.requestSerializer setQueryStringSerializationWithBlock:^NSString *(NSURLRequest *request, id parameters, NSError * __autoreleasing * error) {
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters options:NSJSONWritingPrettyPrinted error:error];
NSString *argString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
return argString;
}];
[sessionManager POST:urlString parameters:parameters progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
if (completion) {
completion(responseObject, nil);
}
} failure:^(NSURLSessionDataTask *task, NSError *error) {
if (completion) {
NSData *errorData = [error.userInfo objectForKey:#"com.alamofire.serialization.response.error.data"];
NSDictionary *responseErrorObject = [NSJSONSerialization JSONObjectWithData:errorData options:NSJSONReadingAllowFragments error:nil];
completion(responseErrorObject, error);
}
}];
For HTTPBody with custom String format
[sessionManager.requestSerializer setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[sessionManager.requestSerializer setQueryStringSerializationWithBlock:^NSString *(NSURLRequest *request, id parameters, NSError * __autoreleasing * error) {
NSString *argString = [self dictionaryToString:parameters];
return argString;
}];
[sessionManager POST:urlString parameters:parameters progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
if (completion) {
completion(responseObject, nil);
}
} failure:^(NSURLSessionDataTask *task, NSError *error) {
if (completion) {
NSData *errorData = [error.userInfo objectForKey:#"com.alamofire.serialization.response.error.data"];
NSDictionary *responseErrorObject = [NSJSONSerialization JSONObjectWithData:errorData options:NSJSONReadingAllowFragments error:nil];
completion(responseErrorObject, error);
}
}];
-(void)postRequest:(NSString *)urlStr parameters:(NSDictionary *)parametersDictionary completionHandler:(void (^)(NSString*, NSDictionary*))completionBlock{
NSURL *URL = [NSURL URLWithString:urlStr];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager POST:URL.absoluteString parameters:parametersDictionary progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseObject
options:kNilOptions
error:&error];
completionBlock(#"Success",json);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(#"Error: %#", error);
completionBlock(#"Error",nil);
}];
}
This method is working fine for AFNetworking 3.0.
Use common NSObject Class method for Calling Wenservices with AFNetworking 3.0
This is my Duplicate Answer but it was Updated with AFNetworking 3.0
First make NSObject Class Like Webservice.h and Webservice.m
Webservice.h
#interface Webservice : NSObject
+ (void)requestPostUrl:(NSString *)strURL parameters:(NSDictionary *)dictParams success:(void (^)(NSDictionary *responce))success failure:(void (^)(NSError *error))failure;
#end
Webservice.m your nsobject.m file is look like this.(add two functions in .m file)
#import "Webservice.h"
#define kDefaultErrorCode 12345
#implementation Webservice
+ (void)requestPostUrl:(NSString *)strURL parameters:(NSDictionary *)dictParams success:(void (^)(NSDictionary *responce))success failure:(void (^)(NSError *error))failure {
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager setResponseSerializer:[AFHTTPResponseSerializer serializer]];
[manager POST:strURL parameters:dictParams progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
if([responseObject isKindOfClass:[NSDictionary class]]) {
if(success) {
success(responseObject);
}
}
else {
NSDictionary *response = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
if(success) {
success(response);
}
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
if(failure) {
failure(error);
}
}];
}
#end
make sure you have to replace your dictionary key with success and
message for handling of responce callback function
Use like this call this common method from any viewcontroller.m and any methods from any viewControllers. for temporary i am using viewDidLoad for calling This WS.
- (void)viewDidLoad {
[super viewDidLoad];
NSDictionary *dictParam = #{#"parameter1":#"value1",#"parameter1":#"value2"};
[Webservice requestPostUrl:#"add your webservice URL here" parameters:dictParam success:^(NSDictionary *responce) {
//Success
NSLog(#"responce:%#",responce);
//do code here
} failure:^(NSError *error) {
//error
}];
}
add your Parameter, values and webservice URL in above method. you can easily use this NSObjcet Class. for more details please visit AFNetworking 3.0 or my old answear with AFNetworking 2.0.
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:log.text, #"email", pass.text, #"password", nil];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
[manager POST:#"add your webservice URL here" parameters:dict progress:nil success:^(NSURLSessionTask *task, id responseObject) {
NSLog(#"%#", responseObject);
}
failure:^(NSURLSessionTask *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
/**
* Services gateway
* Method get response from server
* #parameter -> object: request josn object ,apiName: api endpoint
* #returm -> void
* #compilationHandler -> success: status of api, response: respose from server, error: error handling
*/
+ (void)getDataWithObject:(NSDictionary *)object onAPI:(NSString *)apiName withController:(UIViewController*)controller
:(void(^)(BOOL success,id response,NSError *error))compilationHandler {
controller = controller;
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
// set request type to json
manager.requestSerializer = [AFJSONRequestSerializer serializer];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
// post request to server
[manager POST:apiName parameters:object success:^(AFHTTPRequestOperation *operation, id responseObject) {
// NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:responseObject
options:0
error:&error];
//NSString *JSONString = [[NSString alloc] initWithBytes:[jsonData bytes] length:[jsonData length] encoding:NSUTF8StringEncoding];
////
// check the status of API
NSDictionary *dict = responseObject;
NSString *statusOfApi = [[NSString alloc]initWithFormat:#"%#"
,[dict objectForKey:#"OK"]];
// IF Status is OK -> 1 so complete the handler
if ([statusOfApi isEqualToString:#"1"] ) {
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
compilationHandler(TRUE,responseObject,nil);
} else {
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
NSArray *errorMessages = [responseObject objectForKey:#"messages"];
NSString *message = [errorMessages objectAtIndex:0];
[Utilities showAlertViewWithTitle:apiName message:message];
compilationHandler(FALSE,responseObject,nil);
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSString *message = [NSString stringWithFormat:#"%#",[error localizedDescription]];
NSLog(#"Message is %#", message);
NSString *errorMessage = [NSString stringWithFormat:#"%#",[error localizedDescription]];
if (!([message rangeOfString:#"The request timed out."].location == NSNotFound)) {
[Utilities showAlertViewWithTitle:apiName message:errorMessage];
}
compilationHandler(FALSE,errorMessage,nil);
}];
}
- (instancetype)init {
self = [super init];
if (self) {
[self configureSesionManager];
}
return self;
}
#pragma mark - Private
- (void)configureSesionManager {
sessionManager = [AFHTTPSessionManager manager];
sessionManager.responseSerializer = [AFJSONResponseSerializer serializer];
sessionManager.responseSerializer.acceptableContentTypes = [sessionManager.responseSerializer.acceptableContentTypes setByAddingObject:#"text/html"];
sessionManager.requestSerializer = [AFHTTPRequestSerializer serializer];
sessionManager.requestSerializer.timeoutInterval = 60;
}
#pragma mark - Public
- (void)communicateUsingPOSTMethod:(NSString*)pBaseURL parameterDictionary:(NSDictionary*)pParameterDictionary
success:(void(^)(id))pSuccessCallback failure:(void(^)(NSError* error))pFailiureCallback {
[sessionManager POST:pBaseURL parameters:pParameterDictionary progress:nil success:^(NSURLSessionTask *task, id responseObject) {
pSuccessCallback(responseObject);
} failure:^(NSURLSessionTask *operation, NSError *error) {
pFailiureCallback(error);
}];
}
#import <Foundation/Foundation.h>
#import "UserDetailObject.h"
#import "AFNetworking.h"
#import "XMLReader.h"
//宏定义成功block 回调成功后得到的信息
typedef void (^HttpSuccess)(id data);
//宏定义失败block 回调失败信息
typedef void (^HttpFailure)(NSError *error);
#interface NetworkManager : NSObject<NSXMLParserDelegate, NSURLConnectionDelegate>
#property (strong, nonatomic) NSMutableData *webData;
#property (strong, nonatomic) NSMutableString *soapResults;
#property (strong, nonatomic) NSXMLParser *xmlParser;
#property (nonatomic) BOOL elementFound;
#property (strong, nonatomic) NSString *matchingElement;
#property (strong, nonatomic) NSURLConnection *conn;
//请求水文信息数据
+ (void)sendRequestForSQInfo:(UserDetailObject *)detailObject success:(HttpSuccess)success failure:(HttpFailure)failure;
//get请求
+(void)getWithUrlString:(NSString *)urlString success:(HttpSuccess)success failure:(HttpFailure)failure;
//post请求
+(void)postWithUrlString:(NSString *)urlString parameters:(NSDictionary *)parameters success:(HttpSuccess)success failure:(HttpFailure)failure;
#end
NetworkManager.m
#import "NetworkManager.h"
#implementation NetworkManager
#synthesize webData;
#synthesize soapResults;
#synthesize xmlParser;
#synthesize elementFound;
#synthesize matchingElement;
#synthesize conn;
+ (void)sendRequestForSQInfo:(UserDetailObject *)detailObject success:(HttpSuccess)success failure:(HttpFailure)failure{
NSString *parameter = #"{\"endDate\":\"2015-06-01 08\",\"beginDate\":\"2015-06-01 08\"}";
NSString *urlStr = #"http://10.3.250.136/hwccysq/cxf/water";
NSString *methodName = #"getSqInfo";
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
//回复的序列化
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[[manager dataTaskWithRequest:[self loadRequestWithParameter:parameter url:urlStr methodName:methodName] completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (!error) {
success(responseObject);
} else {
// NSLog(#"Error: %#, %#, %#", error, response, responseObject);
failure(error);
}
}] resume];
}
+ (NSMutableURLRequest *)loadRequestWithParameter:(NSString *)parameter url:(NSString *)urlString methodName:(NSString *)methodName{
NSString *soapMessage =
[NSString stringWithFormat:
#"<?xml version=\"1.0\" encoding=\"utf-8\"?>"
"<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:agen=\"http://agent.water.tjswfxkh.lonwin.com/\" >"
"<soapenv:Body>"
"<agen:%#>"
"<arg0>%#</arg0>"
"</agen:%#>"
"</soapenv:Body>"
"</soapenv:Envelope>", methodName,parameter,methodName
];
// 将这个XML字符串打印出来
NSLog(#"%#", soapMessage);
// 创建URL,内容是前面的请求报文报文中第二行主机地址加上第一行URL字段
NSURL *url = [NSURL URLWithString:urlString];
// 根据上面的URL创建一个请求
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
NSString *msgLengt = [NSString stringWithFormat:#"%ld", [soapMessage length]];
// 添加请求的详细信息,与请求报文前半部分的各字段对应
[req addValue:#"application/soap+xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[req addValue:msgLengt forHTTPHeaderField:#"Content-Length"];
// 设置请求行方法为POST,与请求报文第一行对应
[req setHTTPMethod:#"POST"];
// 将SOAP消息加到请求中
[req setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];
return req;
}
//GET请求
+(void)getWithUrlString:(NSString *)urlString success:(HttpSuccess)success failure:(HttpFailure)failure{
//创建请求管理者
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//内容类型
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:#"application/json",#"text/json",#"text/javascript",#"text/html", nil];
//get请求
[manager GET:urlString parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
//数据请求的进度
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
success(responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
failure(error);
}];
}
//POST请求
+(void)postWithUrlString:(NSString *)urlString parameters:(NSDictionary *)parameters success:(HttpSuccess)success failure:(HttpFailure)failure{
//创建请求管理者
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//内容类型
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:#"application/json",#"text/json",#"text/javascript",#"text/html", nil];
//post请求
[manager POST:urlString parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
//数据请求的进度
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
success(responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
failure(error);
}];
}
#end
then add request in controller
UserDetailObject *detailObject = [[UserDetailObject alloc]init];
[NetworkManager sendRequestForSQInfo:detailObject success:^(id data) {
NSXMLParser *parser = [[NSXMLParser alloc]initWithData:data];
NSError *parseError = nil;
NSDictionary *dict = [XMLReader dictionaryForNSXMLParser:parser error:&parseError];
NSLog(#"JSON: - %#", dict);
} failure:^(NSError *error) {
NSLog(#"%#",error);
}];
https://github.com/Rita5969/afnetwork3.0-for-webservice

how to get return in AFHTTPRequestOperationManager request in afnetworking

Hi i am posting data in using AFHTTPRequestOperationManager class getting the response from server but not able to return data . method return is executed first then success data is coming i want to get the value in return .
this is my code
.h file
#interface ServerRequest : NSObject
{
}
-(NSString *) JsonData:(NSString *)newparams actionmethod:(NSString *)action parameters:(NSDictionary *)params;
.m
#import "ServerRequest.h"
#import "AFNetworking.h"
#implementation ServerRequest
{
}
-(NSDictionary *) getJsonData:(NSString *)anynewparams
actionmethod:(NSString *)action
parameters:(NSDictionary *)params {
NSMutableDictionary *json = [[NSMutableDictionary alloc] init];
NSString *url = #"http://gjkhdhdyi/ghdgd/Rest/";
url = [url stringByAppendingString:action];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
AFJSONRequestSerializer *requestSerializer = [AFJSONRequestSerializer serializer];
[requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Accept"];
manager.requestSerializer = requestSerializer;
[manager
POST:weburl
parameters:params
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
json=responseObject;
// here i am getting data
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
return json;
}
Now i am calling this method in my ViewController class after importing this i called like this
ServerRequest *servercall=[[ServerRequest alloc]init];
returninfo=[servercall getJsonData:nil actionmethod:#"loginuser?" parameters:inputs]
// here i want return data.
issue is here not getting return here . but in Method i am getting . so how to get json data after success Request , how to do this
Your request method uses blocks, which will won't execute immediately, but instead get dispatched/scheduled, so the method returns before the request can complete (thus the nil value) You could refactor your method to use success/error blocks:
.h file
-(void)getJsonData:(NSString *)anynewparams
actionmethod:(NSString *)action
parameters:(NSDictionary *)params
onComplete:(void (^)(NSDictionary *json))successBlock
onError:(void (^)(NSError *error))errorBlock;
.m file
-(void)getJsonData:(NSString *)anynewparams
actionmethod:(NSString *)action
parameters:(NSDictionary *)params
onComplete:(void (^)(NSDictionary *json))successBlock
onError:(void (^)(NSError *error))errorBlock {
NSString *url = #"http://gjkhdhdyi/ghdgd/Rest/";
url = [url stringByAppendingString:action];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
AFJSONRequestSerializer *requestSerializer = [AFJSONRequestSerializer serializer];
[requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Accept"];
manager.requestSerializer = requestSerializer;
[manager POST:weburl parameters:params
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
successBlock(responseObject);
}
failure: ^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
errorBlock(error);
}];
}
Then later:
ServerRequest *servercall=[[ServerRequest alloc] init];
[servercall getJsonData:nil actionmethod:#"loginuser?" parameters:inputs onComplete:^(NSDictionary *json) {
// return json ehre
} onError:^(NSError *error) {
// handle error here
}];
You can try like this also -
.h file
- (NSDictionary *) getJsonData:(NSString *)anynewparams actionmethod:(NSString *)action parameters:(NSDictionary *)params onComplete:(void (^)(NSDictionary *json))successBlock
onError:(void (^)(NSError *error))errorBlock;
.m file
-(NSDictionary *) getJsonData:(NSString *)anynewparams actionmethod: (NSString *)action parameters:(NSDictionary *)params
onComplete:(void (^)(NSDictionary *json))successBlock
onError:(void (^)(NSError *error))errorBlock{
__block id json;
NSString *url = #"http://gjkhdhdyi/ghdgd/Rest/";
url = [url stringByAppendingString:action];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
AFJSONRequestSerializer *requestSerializer = [AFJSONRequestSerializer serializer];
[requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Accept"];
manager.requestSerializer = requestSerializer;
[manager POST:url parameters:params
success:^(AFHTTPRequestOperation *operation, id responseObject)
{
successBlock(responseObject);
}
failure:
^(AFHTTPRequestOperation *operation, NSError *error){
NSLog(#"Error: %#", error);
}];
return json;
}
Call this method in ViewController class
-(void)call_LoginWebService{
returninfo=[[NSDictionary alloc]init];
BaseRequest *basecall=[[BaseRequest alloc]init];
[basecall getJsonData:nil actionmethod:#"LoginUser?" parameters:inputs onComplete:^(NSDictionary *json) {
NSLog(#"alll data here ==%#",json);
returninfo = json;
} onError:^(NSError *error) {
// handle error here
}];
}

AFHTTPRequestOperationManager request POST to server Java

I am developer iOS. I have a problem about AFHTTPRequestOperationManager request POST to server(JBoss) Java. When I request POST with Multipart is good response, and not problem. But, when I request POST only string to server, server show me error:
11:57:19,815 ERROR [UserRest] Problem on login email: null password:
null 11:57:19,817 ERROR [STDERR] java.lang.Exception: MISSING ARGUMENTS
This show me, send parameters null. This method:
AFHTTPRequestOperation *)POST:(NSString *)URLString parameters:(NSDictionary *)parameters success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
I don't understand, why send parameters null.. My code is:
NSString *strURL = #"http://YOUR_IP/YOUR_PATH/login";
__block const NSString *strResultResponse = #"";
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.securityPolicy.allowInvalidCertificates = NO;
AFJSONRequestSerializer *serializerRequest = [AFJSONRequestSerializer serializer];
[serializerRequest setValue:#"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
AFJSONResponseSerializer *serializerResponse = [AFJSONResponseSerializer serializer];
serializerResponse.readingOptions = NSJSONReadingAllowFragments;
serializerResponse.acceptableContentTypes = [NSSet setWithObject:#"application/json"];
manager.requestSerializer = serializerRequest;
manager.responseSerializer = serializerResponse;
NSDictionary *parameters = #{#"email":#"xxxxxx#xxxx.xxxx",#"password":#"xxxx"};
[manager POST:strURL parameters:parameters
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"%#", operation.responseString);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"%#", operation.responseString);
}];
I tried many ways, but not result. Please help me.

Resources