SSL Pinning with AFNetworking 1.x - ios

Im new to the AFNetworking framework and the SSL Pinning.
I already did the :
#define _AFNETWORKING_PIN_SSL_CERTIFICATES_ = 1
but dont think its enough, its correct?
How can i do this?
Heres my current request :
NSArray *info = #{#"action" : #"test"};
NSError * error = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:info options:NSJSONWritingPrettyPrinted error:&error];
NSMutableURLRequest*request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:url]];
NSMutableData *body = [NSMutableData data];
[body appendData:jsonData];
[request setHTTPBody:body];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"content-type"];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:request.URL];
[httpClient registerHTTPOperationClass:[AFHTTPRequestOperation class]];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation
*operation, id responseObject) {
NSError *error;
NSString *responseString = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(#"response String %#",responseString);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#",error.localizedDescription); }];
[operation start];
The request works just fine, but i dont know if its really pinning the ssl.

You must set SSLPinningMode property to AFSSLPinningModeCertificate befor calling start on AFJSONRequestOperation.

Related

AFnetworking Multipart data of image in base64 encoding format

How can i send Base64 image encoded to the server using af networking. I have converted the image in to base 64 but the problem is in sending the image to the server. Iam new to ios so please help me in resolving this issue.
NSString *surl = #"https://xxxxxxxxxxxxx";
surl = [surl stringByAppendingString:userID];
NSLog(#"%#", surl);
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:surl]];
[request setHTTPMethod:#"POST"];
[request setValue:#"multipart/form-data" forHTTPHeaderField:#"Accept"];
NSMutableData *postBody = [NSMutableData data];
[postBody appendData:[base64 dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:postBody];
NSLog(#"postbody%#", postBody);
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]initWithRequest:request];
operation.responseSerializer = [AFHTTPResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON Successsss: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"error: %#",error);
NSHTTPURLResponse *response = (NSHTTPURLResponse *)operation.response;
NSLog(#"statusCode: %ld", (long)response.statusCode);
NSString* ErrorResponse = [[NSString alloc] initWithData:(NSData *)error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] encoding:NSUTF8StringEncoding];
NSLog(#"Error Response:%#",ErrorResponse);
}];
[[NSOperationQueue mainQueue] addOperation:operation];
}

How to trigger NSOperationQueue and get results in block of multiple operation

I already asked question related to NSOperationQueue but I am still around of implementing operation queue with multiples operation. I have following code
NSMutableArray * operationArray = [[NSMutableArray alloc] init];
for (int i =0; i<[documentModelList count]; i++) {
DocumentModel * documentModel = [documentModelList objectAtIndex:i];
NSString *url = [NSString stringWithFormat:#"%#%#/%li", SERVER_URL, DOCUMENTS_DELETE,(long)documentModel.documentID];
[operationArray addObject:[AppHttpClient getDeleteRequest:nil urlQuery:url]];
}
NSOperationQueue *operationQueue = [[NSOperationQueue alloc] init];
// Set the max number of concurrent operations (threads)
[operationQueue setMaxConcurrentOperationCount:operationArray.count];
[operationQueue addOperations:operationArray waitUntilFinished:NO];
+ (AFHTTPRequestOperation *) getDeleteRequest:(NSDictionary *)headerParams urlQuery: (NSString*)action
{
NSString *jsonString = #"";
NSString *authorizationValue = [self setAuthorizationValue:action];
NSString *language = #"en_US";
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:language forHTTPHeaderField:#"Accept-Language"];
[request setValue:authorizationValue forHTTPHeaderField:#"authorization"];
[request setURL:[NSURL URLWithString:action]];
[request setTimeoutInterval:500.0];
[request setHTTPMethod:#"DELETE"];
NSMutableData *postBody = [NSMutableData data];
[postBody appendData:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:postBody];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
return operation;
}
The above code creating operations in loop and adding into operationArray and then add this operation array into operationQueue. Now I want to trigger that and get response of whole array.
Edited
+ (void) gernalDeleteRequest:(NSDictionary *)headerParams urlQuery: (NSString*)action parameters:(NSDictionary*)params
onComplete:(void (^)(id json, id code))successBlock
onError:(void (^)(id error, id code))errorBlock
{
NSString *jsonString = #"";
NSString *authorizationValue = [self setAuthorizationValue:action];
NSString *language = #"en_US";
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:language forHTTPHeaderField:#"Accept-Language"];
[request setValue:authorizationValue forHTTPHeaderField:#"authorization"];
//convert parameters in to json data
if ([params isKindOfClass:[NSDictionary class]]) {
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params
options:NSJSONWritingPrettyPrinted
error:&error];
jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
[request setURL:[NSURL URLWithString:action]];
[request setTimeoutInterval:500.0];
[request setHTTPMethod:#"DELETE"];
NSMutableData *postBody = [NSMutableData data];
[postBody appendData:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:postBody];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSInteger statusCode = [operation.response statusCode];
NSNumber *statusObject = [NSNumber numberWithInteger:statusCode];
successBlock(responseObject, statusObject);
NSLog(#"authentication success");
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSInteger statusCode = [operation.response statusCode];
NSNumber *statusObject = [NSNumber numberWithInteger:statusCode];
id responseObject = operation.responseData;
id json = nil;
NSString *errorMessage = nil;
if (responseObject) {
json = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:&error];
errorMessage = [(NSDictionary*)json objectForKey:#"Message"];
}else{
json = [error.userInfo objectForKey:NSLocalizedDescriptionKey];
errorMessage = json;
}
errorBlock(errorMessage, statusObject);
}];
[[NSOperationQueue mainQueue] addOperation:operation];
}
For the overall status you can create another operation, which can be a block operation, and which uses addDependency: to ensure that it runs after all of the other operations are complete. Add the dependencies in the loop where you create each delete operation.
For each individual status you need to use setCompletionBlockWithSuccess:failure: to get feedback about the results.

How to convert NSURLConnection to AFNetworking?

i want to convert this code to AFNetworking but i have a error. i used
AFNetworking POST to REST webservice this code.
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSString *latest_url = #"url_string";
[request setURL:[NSURL URLWithString:latest_url]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setValue:useragent_string forHTTPHeaderField:#"User-Agent"];
[request setValue:host_string forHTTPHeaderField:#"Host"];
[request setValue:#"keep-alive" forHTTPHeaderField:#"Connection"];
[request setValue:#"keep-alive" forHTTPHeaderField:#"Proxy-Connection"];
[request setTimeoutInterval:30.0];
[request setHTTPBody:postData];
NSError *errorx = nil;
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&errorx];
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSData *jsonData = [json_string dataUsingEncoding:NSUTF8StringEncoding];
NSError *jsonerror;
NSData *get_data_from_request = [ourdelegate do_request:request_url post_array:request_post_array debug:istekdebug];
NSArray *statuses =[NSJSONSerialization JSONObjectWithData: jsonData options: NSJSONReadingMutableContainers error: &jsonerror];
How to convert this code to AFNetworking?
Since you are using post request, here's what you can do with AFHTTPSessionManager. You can also call AFHTTPSessionManager Get method with block invocation.
NSURL *baseURL = [NSURL URLWithString:BaseURLString];
NSDictionary *parameters = #{#"Host": host_string};
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:baseURL];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager POST:#"yourFile.php" parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject) {
NSLog("handle succes");
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog("handle error %#",[error localizedDescription]);
}];
Have fun :)
Since you aren't being specific with the error like rckoenes mentioned above.......
Why don't you just go get PAW from LuckyMarmot
It helps you formulate REST api calls and will translate the request into AFNetworking for you. Phenomenal tool for only $19.99. Worth every penny.

EXC_BAD_ACCESS for AFHTTPRequestOperationManager

First calling for "post method" its working fine using AFHTTPRequestOperationManager. But second time i called get method for same AFHTTPRequestOperationManager got EXC_BAD_ACCESS. Please check my below source and help how to resolve.
FIRST CALLING "POST" METHOD- WORKING FINE
NSString *post =[[NSString alloc] initWithFormat:#"grant_type=client_credentials"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding
allowLossyConversion:YES];
NSMutableURLRequest *request = [[NSMutableURLRequest
alloc] init];
[request setURL:[NSURL URLWithString:#"https://example.com/oauth/token"]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"enctype"];
[request setValue:#"xxxxxxxxxx"] forHTTPHeaderField:#"Authorization"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"enctype"];
[request setHTTPBody:postData];
[request setTimeoutInterval:120];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
manager.securityPolicy.allowInvalidCertificates = YES;
[manager.requestSerializer setTimeoutInterval:120];
[post release];
AFHTTPRequestOperation *operation2 = [[AFHTTPRequestOperation alloc] init];
operation2 = [manager HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
NSHTTPURLResponse *response = (NSHTTPURLResponse *)operation.response;
NSLog(#"Response: %#", operation.responseString);
NSLog(#"%ld", (long)response.statusCode);
NSData* data=[operation.responseString dataUsingEncoding:NSUTF8StringEncoding];
NSString *response1 = [[NSString alloc] initWithBytes:[data bytes] length:[data length] encoding: NSUTF8StringEncoding];
[[NSNotificationCenter defaultCenter] postNotificationName:#"check_auth_token_init" object:[[ResponseHandler instance] parseToken:response1]];
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", operation.responseString);
}];
[operation2 start];
SECOND CALLING "GET" METHOD- EXC_BAD_ACCESS
NSMutableURLRequest *request = [[NSMutableURLRequest
alloc] init];
[request setURL:[NSURL URLWithString:#"https://example.com/stu/groups/"]];
[request setHTTPMethod:#"GET"];
[request setValue:#"testing" forHTTPHeaderField:#"Authorization"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
//Here i tried to internalize "AFHTTPRequestOperationManager" but im getting EXC_BAD_ACCESS Please check attached screen shots
AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] init];
manager.securityPolicy.allowInvalidCertificates = YES;
// Configure Request Operation Manager
[manager setResponseSerializer:[AFJSONResponseSerializer serializer]];
// Send Request
AFHTTPRequestOperation *operation = [manager HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", operation.responseString);
}];
[operation start];
The warning "Method possibly missing a [super dealloc] call" suggests that you're compiling AFNetworking without ARC, which would explain why objects are being prematurely deallocated.
Please follow the installation instructions provided in the AFNetworking README to ensure that everything is configured correctly.

Translating from ASIHTTPRequest to AFNetworking , on iOS

What i want to do is post a json file to my server. I finally did that using ASIHTTPRequest and my code is :
NSURL *url = [NSURL URLWithString:#"http://foo.foo.foo"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setRequestMethod:#"PUT"];
[request addRequestHeader:#"Authorization" value:#"Basic dslfkdsfdsflsdkfslkgflksflksdlfkg"];
[request addRequestHeader:#"Content-Type" value:#"application/json; charset=utf-8"];
[request appendPostData:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
[request startSynchronous];
NSLog(#"%#", [request responseString]);
What i need now is the exact above code translated to AFNetworking. Any ideas??
Thank you for reading my post :)
AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:#"http://foo.foo.foo"]];
client.parameterEncoding = AFJSONParameterEncoding;
[client registerHTTPOperationClass:[AFJSONRequestionOperation class]];
[client setAuthorizationHeaderWithUsername:... password:...];
[client putPath:#"/path/to/resource" parameters:(_your JSON object as a dictionary_)
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"%#", [request responseString]);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];

Resources