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];
}
Related
I want to send JSON data in URL body from my IOS app to server.I searched many SO question but i can't find what i want. If anyone knows how to do with AFNetworking then please let me know.Thanks
This is my code snipped which send parameters
NSMutableDictionary *parameters = [[NSMutableDictionary alloc]init];
[parameters setValue:#"PY" forKey:#"AppSecret"];
[parameters setValue:#"IOS" forKey:#"login_provider"];
[parameters setValue:_txtemail.text forKey:#"email"];
[parameters setValue:_txtpassword.text forKey:#"password"];
[parameters setValue:#"1" forKey:#"ios_device_id"];
AFHTTPSessionManager *managertwo = [[AFHTTPSessionManager alloc]initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
managertwo.requestSerializer = [AFJSONRequestSerializer serializer];
[managertwo.requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[managertwo POST:[NSString stringWithFormat:#"http://capemedics.co.za/Api/user_register/valid_user"] parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(#"success! %#",responseObject);
NSLog(#"%#",parameters);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(#"error: %#", error);
}];
And i am getting error in it. I want to pass JSON data like this in URL Body
{"login_provider": "IOS","email": "%#","password": ”%#“,”ios_device_id": "1"}
Try This
NSString *strData = [[NSString alloc] initWithFormat:#"{\"login_provider\": \"IOS\",\"email\": \"%#\",\"password\": \"%#\",\"ios_device_id\": \"1\"}",self.txtEmail.text,self.txtPassword.text];
NSString *strURL = #"http://capemedics.co.za/Api/user_register/valid_user"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:strURL] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10];
[request setHTTPMethod:#"POST"];
[request setValue: #"YOUR_KEY" forHTTPHeaderField: #"AppSecret"];
[request setValue: #"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody: [strData dataUsingEncoding:NSUTF8StringEncoding]];
AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
op.responseSerializer = [AFJSONResponseSerializer serializer];
[op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
{
if (responseObject)
{
}
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error){
}];
[op start];
It worked before not sure
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL
cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10];
[request setHTTPMethod:#"POST"];
[request setValue: #"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody: [body dataUsingEncoding:NSUTF8StringEncoding]]; /// body is your son string
AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
op.responseSerializer = [AFJSONResponseSerializer serializer];
[op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON responseObject: %# ",responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", [error localizedDescription]);
}];
[op start];
currently i am working on image uploading in ios application and here is my code
AFHTTPRequestOperationManager *man = [[AFHTTPRequestOperationManager alloc]init];
man.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"text/html"];
NSData *imageData = UIImagePNGRepresentation(self.imageView.image);
AFHTTPRequestOperation *op = [man POST:AddGroup parameters:#{ #"userid":#"6",
#"name":self.txtGroupName.text
#"description":self.textViewGroupDescription.text,
#"image":imageData }
constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:imageData name:#"image" fileName:filename mimeType:#"image/png"];
}
success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSLog(#"Success: %# ***** %#", operation.description, operation.responseString);
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Imani" message:#"New Group Succesfully Created.." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil] ;
[alertView show];
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
NSLog(#"Error: %# ***** %#", operation.responseString, error);
}];
[op start];
now i am getting response from successfully from json but image data are passing null in to server any one have idea ?
Thank you.
try this cede to upload image on server.
AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:#"your api link"]];
NSData *imageData = UIImageJPEGRepresentation(self.imgPost.image, 0.5);
NSDictionary *parameters = #{#"param": #"value",
#"param2" : #"value2"
};
AFHTTPRequestOperation *op = [manager POST:#"/api/store/posts/format/json" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
//do not put image inside parameters dictionary as I did, but append it!
[formData appendPartWithFileData:imageData name:#"file" fileName:[NSString stringWithFormat:#"njoyful_%f.jpg",[NSDate timeIntervalSinceReferenceDate]] mimeType:#"image/jpeg"];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Success: %# ***** %#", operation.responseString, responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %# ***** %#", operation.responseString, error);
}];
[op start];
I'm not familiar with AFHTTPRequestOperation so i'll just give you something i'm using that creates json request.
- (NSURLRequest *)convertToRequest:(NSString *)stringURL withDictionary:(NSDictionary *)dictionary
{
NSError *error = nil;
NSData *JSONData = [NSJSONSerialization dataWithJSONObject:dictionary options:0 error:&error];
NSURL *url = [NSURL URLWithString:stringURL];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setHTTPBody: JSONData];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept-Encoding"];
[request setValue:[NSString stringWithFormat:#"%lu", (unsigned long)[JSONData length]] forHTTPHeaderField:#"Content-Length"];
return request;
}
Please check my answer here
This also work for multi image upload. Cheers! :)
AFNetworking How to send a string of post request?
//restrinBASE64STRING is a NSString ,Program error
[manager POST:URLString parameters:restrinBASE64STRING success:^(AFHTTPRequestOperation *operation, id responseObject) {
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
}];
Solve the problem
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:URLString]];
[request setHTTPMethod:#"POST"];
NSMutableData *postBody = [NSMutableData data];
[postBody appendData:[restrinBASE64STRING dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:postBody];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]initWithRequest:request];
operation.responseSerializer = [AFHTTPResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
}];
[[NSOperationQueue mainQueue] addOperation:operation];
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.
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.