AFNetworking upload image with PUT request? - ios

I'm trying upload image to server using AFNetworking with PUT request.-
UIImage* snap = info[UIImagePickerControllerOriginalImage];
NSData *imageData = UIImageJPEGRepresentation(snap, 0.3);
NSMutableString * fullPath = [NSMutableString stringWithString:API_BASE_URL];
[fullPath appendFormat:#"%#%#",API_VERSION,req];
NSURL * url = [NSURL URLWithString:fullPath];
AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:url];
[manager.requestSerializer setValue:[NSString stringWithFormat:#"%#", #kPublicKey] forHTTPHeaderField:#"X-API-KEY"];
[manager.requestSerializer setValue:bodyStr forHTTPHeaderField:#"X-API-DATA"];
NSString *URLString = fullPath;
NSMutableURLRequest *request = [manager.requestSerializer multipartFormRequestWithMethod:#"PUT" URLString:URLString parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:imageData name:#"media" fileName:#"upload.jpg" mimeType:#"image/jpeg"];
} error:nil];
AFHTTPRequestOperation *requestOperation = [manager HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id responseObject) {
//success
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"failure...");
}];
[requestOperation start];
I'm taking image using iPhone camera and upload it to server but it takes too much time to process and images uploaded on server are in huge size(~10-12MB) although i'm trying to compress the image?
What i'm doing wrong?Any suggestion or sample code would be appreciated.

NSData *imageData = UIImageJPEGRepresentation(snap, 1.0);
The second argument in UIImageJPEGRepresentation denotes the compression quality of the image.As per Apple documentation :
compressionQuality :
The quality of the resulting JPEG image, expressed as a value from 0.0 to 1.0. The value 0.0 represents the maximum compression (or lowest quality) while the value 1.0 represents the least compression (or best quality).
Try reducing this to a number which balances the quality of image and speed of upload.

// manager needs to be init'd with a valid baseURL
NSURL *baseURL = [AfarHTTPSessionManager sharedManager].baseURL;
AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:baseURL];
NSData *imageData = UIImageJPEGRepresentation(draftHighlight.largeImage, 1);
// need to pass the full URLString instead of just a path like when using 'PUT' or 'POST' convenience methods
NSString *URLString = [NSString stringWithFormat:#"%#%#", baseURL, _the_rest_of_your_path];
NSMutableURLRequest *request = [manager.requestSerializer multipartFormRequestWithMethod:#"PUT" URLString:URLString parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:imageData name:kCreateHighlightAPIKeyImage fileName:#"highlight_image.jpg" mimeType:#"image/jpeg"];
}];
// 'PUT' and 'POST' convenience methods auto-run, but HTTPRequestOperationWithRequest just
// sets up the request. you're responsible for firing it.
AFHTTPRequestOperation *requestOperation = [manager HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id responseObject) {
// success
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// failure
}];
// fire the request
[requestOperation start];

Related

Upload Multiple Images using AFNetworking in IOS

I know its asked many times. But i'm facing some problem that i want to send multiple images to the server. The scenario is that , i have used a custom third party library for the selection of multiple images. After user select the images , the images comes in an array. The array are of two types, 1st array carries the name of images which user select no matters how many images he/she select and 2nd is the file path array of images , that array contains the array paths. I have three parameters while POST request 1st is name in which images name array comes, 2nd is ID in which id is pass to which these images are sent and third is images in which the images are. In my code i have used AFHTTPRequestOperationManager but i'm getting error on the header fie that this class had no header file in AFNetworkk folder which i used in my project. My code is this,
-(void)Images{
AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:#"My URL"]];
int i=0;
for(UIImage *eachImage in _arrai)
{
NSData *imageData = UIImagePNGRepresentation([UIImage imageNamed:#"mainImage"]);
[formData appendPartWithFileData:imageData name:[NSString stringWithFormat:#"file%d",i ] fileName:[NSString stringWithFormat:#"file%d.jpg",i ] mimeType:#"image/jpeg"];
i++;
}
NSDictionary *parameters = #{#"name":_arrainame, #"property_id" : Propid, #"image" : _arrai};
AFHTTPRequestOperation *op = [manager POST:#"mainImage" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
//do not put image inside parameters dictionary as I did, but append it!
[formData appendPartWithFileData:imageData name:#"userfile" fileName:#"cat1.png" mimeType:#"image/png"];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Success: %# ***** %#", operation.responseString, responseObject);
} failure:^(AFHTTPRequestOperation operation, NSError error) {
NSLog(#"Error: %# ***** %#", operation.responseString, error);
}];
[op start];
}
NSDictionary *parameters = #{#"name":_arrainame, #"property_id" : Propid};
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:#"POST" URLString:#"http://example.com/upload" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
int i=0;
for(NSString *eachImagePath in _arrai)
{
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:eachImagePath];
[formData appendPartWithFileURL:fileURL name:#"imageParamter" fileName:[NSString stringWithFormat:#"file%d.jpg",i ] mimeType:#"image/jpeg" error:nil];
i++;
}
} error:nil];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSURLSessionUploadTask *uploadTask;
uploadTask = [manager
uploadTaskWithStreamedRequest:request
progress:nil
completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (error) {
NSLog(#"Error: %#", error);
} else {
NSLog(#"%# %#", response, responseObject);
}
}];
[uploadTask resume];
Try this

How To Send NSData with AFNetworking 3 Without Using AFMultipartFormData

I am trying to send wav file as a NSData to rest service with AFNetworking 3. I figured out how to send with AFMultipartFromData but i got an error like that
errorMessage = "Can Not Map Content-Type String multipart/form-data; boundary=Boundary+02588C5 To Media Type ";
When i spoke with the guy who created rest service then he told me i have to send just NSData not anything like AFMultipartFormData. I need some help here because i could not find any way to send "just" NSData.
My code is below;
NSURL *URL = [NSURL URLWithString:#"http://xxxMyService"];
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
configuration.HTTPAdditionalHeaders = #{#"xx": #"yy ; zz"};
AFHTTPSessionManager *manager2 = [[AFHTTPSessionManager alloc] initWithBaseURL:URL sessionConfiguration:configuration];
manager2.responseSerializer = [AFJSONResponseSerializer serializer];
//I converted wav file to NSData
NSData *data=[self setVoiceRecordToNSData];
[manager2 POST:#"http://xxxMyService" parameters:nil
constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
{
[formData appendPartWithFileData:data name:#"data" fileName:#"Path.wav" mimeType:#"audio/wav"];
}
progress:nil success:^(NSURLSessionTask *task, id responseObject
{ NSLog(#"JSON: %#", responseObject);}
failure:^(NSURLSessionTask *operation, NSError *error) {
NSLog(#"Error: %#", error); }];
Try add this code before POST
manager2.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"multipart/form-data"];

AFNetworking 3.x post request with data and image

I want to send a post request to my backend that contains some data and an UIImage as NSData Object. Problem is, I have no idea how to to that with AFNetworking 3.0.
My code so far:
NSString *url = [NSString stringWithFormat:#"%#%#", baseURL, #"/postProjectNote"];
NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
[dic setObject:session forKey:#"session"];
[dic setObject:timestamp forKey:#"timestamp"];
[dic setObject:project_id forKey:#"project_id"];
[dic setObject:type forKey:#"type"];
NSData imagedata = UIImageJPEGRepresentation(myUIImage, 0.8);
I don't need any sort of progress bar. I just need an result if the request was successful or not. The backend (Laravel 5) gives me a json string. I need to sent it with form-data.
Can you help me getting started?
Use this code to post an image using AFNetworking:
AFHTTPRequestOperationManager* manager = [[AFHTTPRequestOperationManager alloc] init];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"application/json"];
NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
NSMutableDictionary *paramDict = [NSMutableDictionary new]; // Add additional parameters here
AFHTTPRequestOperation *op = [manager POST:UPDATE_PROFILE_IMAGE parameters:paramDict constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:imageData name:#"file" fileName:#"filename" mimeType:#"image/jpeg"];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
if (success) {
// Success
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// Failure
}];
[op start];
NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc]initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager.requestSerializer setValue:token forHTTPHeaderField:#"Authorization"];
[manager.requestSerializer setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
manager.responseSerializer.acceptableContentTypes =[NSSet setWithObjects:#"text/html",#"application/json",nil];
[manager POST:encoded parameters:"the params you want to pass" constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
[formData appendPartWithFileData:imageData
name:"image name with timestamp"
fileName:#"image_upload_file"
mimeType:[NSString mimeTypeForImageData:data]];
} progress:^(NSProgress * _Nonnull uploadProgress) {
//DLog(#"Progress = %#",uploadProgress);
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
//DLog(#"Response = %#",responseObject);
completion(YES,responseObject,nil);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
completion(NO,nil,error);
//DLog(#"Error: %#", error);
}];

AFNetworking - Upload video along with other parameters

I want to upload video to web service along with some other parameters. I want to upload userID, videoID and video to web service. While uploading, all the parameters other than video is being sent to web service. I've checked at web service end, and the video is not coming with the request. I am using the following code.
- (void)uploadVideoAtLocalPath:(NSString *)videoPath videoID:(NSString *)videoID userID:(NSString *)userID {
NSString *strServerURL = #"www.mysite.com/user/uploadVideo";
NSURL *URL = [NSURL URLWithString:strServerURL];
AFHTTPClient *client = [AFHTTPClient clientWithBaseURL:URL];
NSMutableURLRequest *request = [client multipartFormRequestWithMethod:#"POST" path:#"" parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
// userID
NSData *userIDData = [userID dataUsingEncoding:NSUTF8StringEncoding];
[formData appendPartWithFormData:userIDData name:#"userID"];
// videoID
NSData *videoIDData = [videoID dataUsingEncoding:NSUTF8StringEncoding];
[formData appendPartWithFormData:videoIDData name:#"videoID"];
// video
NSData *videoData = [NSData dataWithContentsOfURL:[NSURL fileURLWithPath:videoPath]];
[formData appendPartWithFileData:videoData name:#"video" fileName:#"video.mov" mimeType:#"video/quicktime"];
}];
[request setURL:URL];
[request setTimeoutInterval:60.0];
[request setHTTPMethod:#"POST"];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[AFHTTPRequestOperation addAcceptableStatusCodes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(100, 500)]];
[operation setCompletionBlockWithSuccess: ^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Response String: %#", operation.responseString);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Failure: %#", error);
}];
[client enqueueHTTPRequestOperation:operation];
}
Could anyone let me know whether I am doing it correct? If not, could anyone please tell me how to upload video to web service along with other parameters?
Thanks Everyone!
I'm not well in this method. I had the same issue. But, i have fixed it like mixing of POST & GET methods. I just sent my parameters as GET method like below -
NSString *strServerURL = [NSString stringWithFormat:#"www.mysite.com/user/uploadVideo&userID=%d&videoID=%d", 1, 55];
and, sent my video data in POST method as per your method -
NSMutableURLRequest *request = [client multipartFormRequestWithMethod:#"POST" path:#"" parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
// video
NSData *videoData = [NSData dataWithContentsOfURL:[NSURL fileURLWithPath:videoPath]];
[formData appendPartWithFileData:videoData name:#"video" fileName:#"video.mov" mimeType:#"video/quicktime"];
}];
You better try to modify your webservice and try like above way. It should works.
Cheers!

send image along with other parameters with AFNetworking

I am updating an old application code which used ASIHTTPRequest with AFNetworking. In my case, I am sending a bench of data to API, these data are different types: Image and other.
Here is the code I adopt so far, implementing an API client, requesting a shared instance, prepare the params dictionary and send it to remote API:
NSMutableDictionary *params = [NSMutableDictionary dictionary];
[params setValue:#"Some value" forKey:aKey];
[[APIClient sharedInstance]
postPath:#"/post"
parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
//some logic
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//handle error
}];
What would be the case when I want to add an image to the params dictionary?
With ASIHTTPRequest, I used to do the following:
NSData *imgData = UIImagePNGRepresentation(anImage);
NSString *newStr = [anImageName stringByReplacingOccurrencesOfString:#"/"
withString:#"_"];
[request addData:imgData
withFileName:[NSString stringWithFormat:#"%#.png",newStr]
andContentType:#"image/png"
forKey:anOtherKey];
I digged into AFNetworking documentation and found they appending the image in an NSMutableRequest like this:
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
NSData *imageData = UIImageJPEGRepresentation([UIImage imageNamed:#"avatar.jpg"], 0.5);
NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:#"POST" path:#"/upload" parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
[formData appendPartWithFileData:imageData name:#"avatar" fileName:#"avatar.jpg" mimeType:#"image/jpeg"];
}];
How should I mix this together on a neat way to integrate my image data into the APIClient request? Thanx in advance.
I have used same AFNetworking to upload image with some parameter. This code is fine working for me. May be it will help out
NSData *imageToUpload = UIImageJPEGRepresentation(uploadedImgView.image, 1.0);//(uploadedImgView.image);
if (imageToUpload)
{
NSDictionary *parameters = [NSDictionary dictionaryWithObjectsAndKeys:keyParameter, #"keyName", nil];
AFHTTPClient *client= [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:#"http://------"]];
NSMutableURLRequest *request = [client multipartFormRequestWithMethod:#"POST" path:#"API name as you have" parameters:parameters constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
[formData appendPartWithFileData: imageToUpload name:#"image" fileName:#"temp.jpeg" mimeType:#"image/jpeg"];
}];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSDictionary *jsons = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:nil];
//NSLog(#"response: %#",jsons);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
if([operation.response statusCode] == 403)
{
//NSLog(#"Upload Failed");
return;
}
//NSLog(#"error: %#", [operation error]);
}];
[operation start];
}
Good Luck !!
With AFNetworking 2.0.1 this code worked for me.
-(void) saveImage: (NSData *)imageData forImageName: (NSString *) imageName {
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSString *imagePostUrl = [NSString stringWithFormat:#"%#/v1/image", BASE_URL];
NSDictionary *parameters = #{#"imageName": imageName};
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:#"POST" URLString:imagePostUrl parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:imageData name:#"image" fileName:imageName mimeType:#"image/jpeg"];
}];
AFHTTPRequestOperation *op = [manager HTTPRequestOperationWithRequest:request success: ^(AFHTTPRequestOperation *operation, id responseObject) {
DLog(#"response: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
DLog(#"Error: %#", error);
}];
op.responseSerializer = [AFHTTPResponseSerializer serializer];
[[NSOperationQueue mainQueue] addOperation:op];
}
If JSON response is needed use:
op.responseSerializer = [AFJSONResponseSerializer serializer];
instead of
op.responseSerializer = [AFHTTPResponseSerializer serializer];

Resources