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

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.

Related

objective-c HTTP POST send request as form

I have used POST method to call API with header values and params for body on my application.
The server only accepts forms in the format
"form": {
"action" : "login",
"user" : "311"
},
When we use code
NSString *urlString = [NSString stringWithFormat:#"%#", url_string];
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSError *error;
NSDictionary *parameters = #{#"action": #"login", #"user": #"311"};
NSString *params = [self makeParamtersString:parameters withEncoding:NSUTF8StringEncoding];
NSData *jsonData2 = [params dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody: jsonData2];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:ourBlock];
My form looks like this
form = {
action = login;
user = 311;
};
Can you produce the result you want?
Could you please help me to solve this issue.
Try
NSString *urlString = [NSString stringWithFormat:#"%#", url_string];
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSError *error;
NSDictionary *parameters = #{#"action": #"login", #"user": #"311"};
NSData *jsonData = [NSJSONSerialization dataWithJSONObject: parameters options:0 error:&error];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody: jsonData];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:ourBlock];
How about change the parameters like this.
NSDictionary *parameters = #{#"form":#{#"action": #"login", #"user": #"311"}};
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters options:NSJSONWritingPrettyPrinted error:nil];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request addValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody: jsonData];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:ourBlock];
Try This if you need base64 encoding
NSMutableDictionary *param = [#{#"form":#{#"action": #"login", #"user": #"311"}} mutableCopy];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:serviceURL];
NSString *strEncoded = [self encodeParameters:param];
NSData *requestData = [strEncoded dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:requestData];
[request setValue:[NSString stringWithFormat:#"%lu",(unsigned long)requestData.length] forHTTPHeaderField:#"Content-Length"];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
// Function encodeParameters
+(NSString *)encodeParameters:(NSDictionary *)dictEncode
{
// Encode character set as per BASE64
NSCharacterSet *URLBase64CharacterSet = [[NSCharacterSet characterSetWithCharactersInString:#"/+=\n"] invertedSet];
NSMutableString *stringEncode = [[NSMutableString alloc] init];
NSArray *allKeys = [dictEncode allKeys];
for (int i = 0;i < allKeys.count; i++) {
NSString *key = [allKeys objectAtIndex:i];
if([dictEncode valueForKey:key])
{
[stringEncode appendFormat:#"%#=%#",key,[[dictEncode valueForKey:key] stringByAddingPercentEncodingWithAllowedCharacters:URLBase64CharacterSet]];
}
if([allKeys count] > i+1)
{
[stringEncode appendString:#"&"];
}
}
return stringEncode;
}
Try this
NSURL * url = [NSURL URLWithString:#"%#",url_string];
NSURLSessionConfiguration * config = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession * session = [NSURLSession sessionWithConfiguration:config];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
request.HTTPMethod = #"POST";
NSDictionary * paramters = [NSDictionary dictionaryWithObjectsAndKeys:#"login",#"action",#"311",#"user", nil]; // [NSDictionary dictionaryWithObjectsAndKeys:#"value",#"key", nil];
NSDictionary *params = #{#"form": paramters};
NSError *err = nil;
NSData *jsonData2 = [NSJSONSerialization dataWithJSONObject:params options:0 error:&err];
Try this,
NSString *parameters = #"\"form\":{\"action\" : \"login\", \"user\" : \"311\"}";
NSData *jsonData2 = [parameters dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody: jsonData2];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:ourBlock];
NSError *error;
NSDictionary *parameters = #{#"form": #{#"action": #"login", #"user": #"311"}};
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters
options:NSJSONWritingPrettyPrinted error:&error];
request.HTTPBody = jsonData
//Using NSURLSession is better option than using NSURLConnection
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSHTTPURLResponse* respHttp = (NSHTTPURLResponse*) response;
if (!error && respHttp.statusCode == 200) {
NSDictionary* respondData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
NSLog(#"%#", respondData);
} else{
NSLog(#"%#", error);
}
}];
[dataTask resume];
Try AFNetwoking
NSString *urlString = [NSString stringWithFormat:#"URL"];
NSDictionary *para= #{#"action": #"login", #"user": #"311"};
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"text/html"];
[manager POST:urlString parameters:para success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];

How to POST { "username"="usernameValue" "password"="passsworValue" } as json body in objective c

I tried Like this..
-(void)GetCartIdDetails{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSString *post = [NSString stringWithFormat:#"username=%#&pasword=%#",self.TextUsername.text,self.TextPassword.text];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu",(unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://192.168.0.21/mahroosa/rest/V1/integration/customer/token"]];
[request setValue:#"application/json; charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:postData];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
//MultiThreading
if (postData){
dispatch_async(dispatch_get_main_queue(), ^{
[[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
//removing Double Qoutes From String
NSString *Replace =[requestReply stringByReplacingOccurrencesOfString:#"\"" withString:#""];
NSLog(#"requestReply: %#", Replace);
}] resume];
});
}
});
}
Using AFNetworking:
-(void)Gettok {
NSString* URLString = [NSString stringWithFormat:#"http://192.168.0.21/mahroosa/rest/V1/integration/customer/token"];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
AFJSONRequestSerializer *requestSerializer = [AFJSONRequestSerializer serializer];
[requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
manager.requestSerializer = requestSerializer;
NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
[params setObject:self.TextUsername.text forKey:#"username"];
[params setObject:self.TextPassword.text forKey:#"password"];
[manager POST:URLString parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSError * error;
NSArray *result = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:&error];
NSLog(#"--------------------respons : %#--------------------",result);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(#"----------------------Error ; %#------------------------------",error);
}];
}
The content type of the request body. Set this value "Content-Type:application/json"
In response i get decode error message.I already got the get JSON getrequest working in AFNetworking but this post request is giving me some problems. Thanks for help in advance.
In the first NSURLSession style you don't send json to the service. Try it like this:
-(void)GetCartIdDetails{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSDictionary *dict = #{#"username":self.TextUsername.text,
#"password":self.TextPassword.text};
NSData *postData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
NSString *postLength = [NSString stringWithFormat:#"%lu",(unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://192.168.0.21/mahroosa/rest/V1/integration/customer/token"]];
[request setValue:#"application/json; charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:postData];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
//MultiThreading
if (postData){
dispatch_async(dispatch_get_main_queue(), ^{
[[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
//removing Double Qoutes From String
NSString *Replace =[requestReply stringByReplacingOccurrencesOfString:#"\"" withString:#""];
NSLog(#"requestReply: %#", Replace);
}] resume];
});
}
});
}

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];
}

Create and send JSON data to server using Objective C

I'm trying to send JSON data to server side using POST method, but my code gives null JSON value. I am using Objective C where I fetch data from textField and convert it into string, but after that while converting this value to JSON object, it gives null value. Don't know what to do.
Here is my code:
- (IBAction)loginAction:(UIButton *)sender
{
NSString *post = [NSString stringWithFormat:#"Username=%#&Password=%#" ,self.userNameField.text,self.passwordField.text];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding];
postData = [postData subdataWithRange:NSMakeRange(0, [postData length] - 1)];
NSData*jsonData = [NSJSONSerialization JSONObjectWithData:postData options:NSJSONReadingMutableContainers error:nil];
NSString *postLength = [NSString stringWithFormat:#"%d",[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://172.31.144.227:8080/Analytics/rest/login/post"]]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length" ];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Current-Type"];
[request setHTTPBody:jsonData];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[theConnection start];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
}
-(void)MessagePost{
NSString * post =[NSString stringWithFormat:#"http://url.com/clients/project_id=%#&user_id=58&question=%#&send_enquiry=Send",[[self.recordchat objectForKey:#"id"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],[[_txtfield text] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSLog(#"%#",post);
NSData *postdata= [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength=[NSString stringWithFormat:#"%lu",(unsigned long)[postdata length]];
NSMutableURLRequest *request= [[NSMutableURLRequest alloc]init];
[request setURL:[NSURL URLWithString:post]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postdata];
NSError *error;
NSURLResponse *response;
postdata=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *returnstring=[[NSString alloc]initWithData:postdata encoding:NSUTF8StringEncoding];
NSLog(#"String : %#",returnstring);
if (postdata){
NSDictionary *dict= [NSJSONSerialization JSONObjectWithData:postdata options:NSJSONReadingMutableContainers error:nil];
NSDictionary* latestLoans = [dict objectForKey:#"status"];
NSLog(#"Status dict = %#",latestLoans);
} else{ NSLog(#"Error while posting messages.");}}
instead of writing NSString *post = [NSString stringWithFormat:#"Username=%#&Password=%#" ,self.userNameField.text,self.passwordField.text];
you should use this
NSMutableDictionary *post = [[NSMutableDictionary alloc]init];
[post setValue:self.userNameField.text forKey:#"Username"];
[post setValue:self.passwordField.text forKey:#"Password"];
Try this -
- (IBAction)loginAction:(UIButton *)sender
{
NSDictionary *dictDetails = #{
#"Username" : self.userNameField.text,
#"Password" : self.passwordField.text
};
NSString *jsonRequest = [dict JSONRepresentation];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"http://172.31.144.227:8080/Analytics/rest/login/post"]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSData *requestData = [NSData dataWithBytes:[jsonRequest UTF8String] length:[jsonRequest length]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody: requestData];
[request setValue:[NSString stringWithFormat:#"%lu", (unsigned long)
[requestData length]] forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Current-Type"];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[theConnection start];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
}
Finally I wrote the correct code and it's working fine now. Please suggest me If any further modification is required..
Thank you all for your time and support..
Here is my code:
- (IBAction)loginAction:(UIButton *)sender
{
NSMutableDictionary *post = [[NSMutableDictionary alloc]init];
[post setValue:self.userNameField.text forKey:#"username"];
[post setValue:self.passwordField.text forKey:#"password"];
NSArray* notifications = [NSArray arrayWithObjects:post, nil];
NSError *writeError = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:notifications options:kNilOptions error:&writeError];
NSString *postLength = [NSString stringWithFormat:#"%d",[jsonData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://172.31.144.227:8080/Analytics/rest/login"]]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length" ];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:jsonData];
NSLog(#"JSON Summary: %#", [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]);
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[theConnection start];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(#"Response Error= %#", response);
if ([response statusCode] >=200 && [response statusCode] <300)
{
NSData *responseData = [[NSData alloc]initWithData:urlData];
NSMutableDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:nil];
NSLog(#"Random Output= %#", jsonObject);
[self performSegueWithIdentifier:#"DASHBOARDSEGUE" sender:sender];
}else {
[self alertStatus:#"Connection Failed" :#"Login Failed!"];
}
}

SSL Pinning with AFNetworking 1.x

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.

Resources