Post a image using AFNetworking? - ios

How to post a image using AFNetworking.i am using below code to post an image.but image is not uploading to server.After posting image i am getting this link in result "http://thisisswitch.com:8084/SmartSwitchService/UserImages/69684177-4601-4665-8890-5424e3fbff73.png".
Can anyone tell me what the problem in code ?
Here is my Code:
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:BaseUrl]];
NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:#"POST" path:posturl parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFormData:imgData name:#"image"];
}];
[httpClient registerHTTPOperationClass:[AFHTTPRequestOperation class]];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
NSDictionary *dict = (NSDictionary *)JSON;
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
}];
[operation start];

From the Github read me:
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSURL *URL = [NSURL URLWithString:#"http://example.com/upload"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSURL *filePath = [NSURL fileURLWithPath:#"file://path/to/image.png"];
NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:filePath progress:nil completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
if (error) {
NSLog(#"Error: %#", error);
} else {
NSLog(#"Success: %# %#", response, responseObject);
}
}];
[uploadTask resume];

Here's how I'm doing it (in AFNetworking 2.x):
- (void)requestWithFormData:(void (^)(id <AFMultipartFormData> formData))formBlock
withParams:(NSDictionary *)params
webservicePath:(NSString *)webservicePath
success:(void (^)(AFHTTPRequestOperation *operation, id jsonDictionary))successBlock
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failureBlock
{
// Handle request for file upload
AFHTTPRequestOperation *op = [self.manager POST:webservicePath
parameters:params
constructingBodyWithBlock:formBlock
success:success
failure:failureBlock];
[op start];
}
Then I use it as per the following:
void (^formBlock)(id <AFMultipartFormData> formData) = ^(id <AFMultipartFormData>formData)
{
NSData *data1 = UIImagePNGRepresentation(profileImage);
[formData appendPartWithFileData:data1 name:#"file" fileName:#"picture.png" mimeType:#"image/png"];
};
[networkingUtil requestWithFormData:formBlock
withParams:params
webservicePath:#"myserver.com/upload"
success:successBlock
failure:failureBlock];
Your server should handle the form data and look for file.

Related

upload audio with afnetworking?

Can anyone tell me how to upload audio files with the help of AFNetworking on a server in iOS? Is this ok?
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager POST:urlString parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:imageData
name:#"files"
fileName:audio mimeType:#"mp3"];
[formData appendPartWithFormData:[key1 dataUsingEncoding:NSUTF8StringEncoding]
name:#"key1"];
[formData appendPartWithFormData:[key2 dataUsingEncoding:NSUTF8StringEncoding]
name:#"key2"];
// etc.
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Response: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
You can use AFURLSessionManager to make an upload task, here's the way:
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSURL *URL = [NSURL URLWithString:#"http://example.com/upload"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSURL *filePath = [NSURL fileURLWithPath:#"file://path/to/image.png"];
NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:filePath progress:nil completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
if (error) {
NSLog(#"Error: %#", error);
} else {
NSLog(#"Success: %# %#", response, responseObject);
}
}];
[uploadTask resume];

AFNetworking Json post image

I studied with objective C programming . I don't know how to post image from the library to the api json (I took the picture from library use UIImagePickerController) . Thanks!
My json api:
http://i.stack.imgur.com/DLKZG.png
- (IBAction)btnAddBook:(id)sender {
AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:#"http://192.168.1.54"]];
NSData *imageData = UIImageJPEGRepresentation(self.ivPickedImage.image, 1);
NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
[params setValue:self.tfTitle.text forKey:#"title"];
[params setValue:self.tfPrice.text forKey:#"price"];
[params setValue:self.tfProem.text forKey:#"proem"];
[params setValue:#"Vietnamese" forKey:#"language"];
AFHTTPRequestOperation *op = [manager POST:#"/api/books" parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:imageData name:#"file" fileName:#"photo.jpg" 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];
Please use this below code:
NSDictionary *requestDictionary = [NSDictionary dictionaryWithObjectsAndKeys:abc.text, #"firstkey",xyz.text, #"secondkey" nil];
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:#"POST" URLString:#"YOUR API URL" parameters:requestDictionary constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
{ [formData appendPartWithFileData:imageData name:#"profile_pic" fileName:#"photo.jpg" mimeType:#"image/jpeg"];
}
} error:nil];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSProgress *progress = nil;
NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:&progress completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
NSLog(#"%#", response);
if (error) {
} else {
}
}];
[uploadTask resume];
Hope this helps.
By using AFNetworking multipart request. you can post image as data. here are the completed block of how to post image as multipart using AFNetworking
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:#"POST" URLString:#"http://example.com/upload" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileURL:[NSURL fileURLWithPath:#"file://path/to/image.jpg"] name:#"file" fileName:#"filename.jpg" mimeType:#"image/jpeg" error:nil];
} error:nil];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSURLSessionUploadTask *uploadTask;
uploadTask = [manager
uploadTaskWithStreamedRequest:request
progress:^(NSProgress * _Nonnull uploadProgress) {
// This is not called back on the main queue.
// You are responsible for dispatching to the main queue for UI updates
dispatch_async(dispatch_get_main_queue(), ^{
//Update the progress view
[progressView setProgress:uploadProgress.fractionCompleted];
});
}
completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (error) {
NSLog(#"Error: %#", error);
} else {
NSLog(#"%# %#", response, responseObject);
}
}];
[uploadTask resume];
AFNetworking
Here your image is not passed as JSON. By using AFNetworking multipart request, all your request parameter passed as JSON and Image/Video that passed as NSData. where NSData is divided in multiple packets.
Thanks

AFNetworking POST non JSON String

I am trying to create a POST request by using AFNetworking library.
[self.manager POST:url parameters:parameters success:^(AFHTTPRequestOperation *operation, id response)
{
// CODE
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
// CODE
}];
Is there a way to post a simple string (not a JSON one) as a request body parameters by using AFNetworking?
Yes this is how you do it:
NSString *someString = #"SomeString";
NSData* stringData = [someString dataUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:#"someUrlString"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20];
[request setHTTPMethod:#"POST"];
[request setHTTPBody: stringData ];
AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
//Success Block
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//failure Block
}];
[op start];

AFnetworking is not uploading image to server

Hello i am new to afnetworking, i want to upload image at server path from ios sdk. below is code for afnetworking,
NSData *imageToUpload = UIImageJPEGRepresentation(selectedImageView.image, 90);
AFHTTPClient *client= [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:#"http://192.168.0.100//smart_attendance/api/employeeImage.php"]];
NSMutableURLRequest *request = [client multipartFormRequestWithMethod:#"POST" path:#"employee_images/large/" parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
[formData appendPartWithFileData: imageToUpload name:#"file" fileName:#"temp.jpeg" mimeType:#"image/jpeg"];
}];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *response = [operation responseString];
NSLog(#"response: [%#]",response);
// [MBProgressHUD hideHUDForView:self.view animated:YES];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//[MBProgressHUD hideHUDForView:self.view animated:YES];
if([operation.response statusCode] == 403){
NSLog(#"Upload Failed");
return;
}
NSLog(#"error: %#", [operation error]);
}];
[operation start];
SERVER RESPONSE IS
AFNetworkingOperationFailingURLRequestErrorKey=<NSMutableURLRequest
http://192.168.0.102/trackingwebsite/tree_images/large/>,
NSErrorFailingURLKey=http://192.168.0.102/trackingwebsite/tree_images/large/,
NSLocalizedDescription=Expected status code in (200-299), got 404,
AFNetworkingOperationFailingURLResponseErrorKey=<NSHTTPURLResponse: 0x98671e0>}
Try out this for url.
NSString *imgUrl=[imageURLString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url=[NSURL URLWithString:imgUrl];
Also your path string is not proper i guess.
Hope that helps.
welll i am using this way and its working fine.
NSString* imageName = #"_image.png";
[[AFAPIClient sharedClient]initWithBaseURL:[NSURL URLWithString:BaseUrl]];
NSMutableURLRequest *request = [[AFAPIClient sharedClient] multipartFormRequestWithMethod:#"POST" path:[NSString stringWithFormat:#"%#%#",BaseUrl,sign_up.php] parameters:dict constructingBodyWithBlock: ^(id <AFMultipartFormData>formData)
{
[formData appendPartWithFileData:UIImagePNGRepresentation([dict objectForKey:#"image"]) name:#"image" fileName:imageName mimeType:#"image/png"];
}];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
{
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
}];
[[AFAPIClient sharedClient]enqueueHTTPRequestOperation:operation];
[operation release];
edited
AFHTTPClient *client= [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:#"http://192.168.0.100/smart_attendance/api/employeeImage.php"]];
NSMutableURLRequest *request = [client multipartFormRequestWithMethod:#"POST" path:#"http://192.168.0.100/smart_attendance/api/employeeImage.php"
parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
[formData appendPartWithFileData:imageToUpload name:#"file" fileName:#"temp.jpeg" mimeType:#"image/jpeg"];
}];

iOS Image upload via AFNetworking 2.0

I've been looking examples for the new AFNetworking 2.0 to upload images.
But I'm hitting wall and couldn't figure out what's wrong with the code.
So this is the code I used
NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSURL *URL = [NSURL URLWithString:#"http://myserverurl.com"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromData:imageData progress:nil completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
if (error) {
NSLog(#"Error: %#", error);
} else {
NSLog(#"Success: %# %#", response, responseObject);
}
}];
[uploadTask resume];
TIA
I ended up using the multi-part request
UIImage *image = [info valueForKey:UIImagePickerControllerOriginalImage];
NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = #{#"foo": #"bar"};
[manager POST:#"http://example.com/resources.json" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFormData:imageData name:#"image"];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Success: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];

Resources