AFNetworking upload image using AFHTTPClient - ios

My question is why AFHTTPClient is slow to upload image. I am using the below code for uploading
NSData *imageToUpload = UIImageJPEGRepresentation(uploadedImgView.image, 1.0);
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];

It might be happen that your image is large and taking time to upload Or you can use latest AFNetworking and can track progress while upload image.
NSData *imageToUpload = UIImageJPEGRepresentation(uploadedImgView.image, 1.0);
NSDictionary *parameters = [NSDictionary dictionaryWithObjectsAndKeys:keyParameter, #"keyName", nil];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:#"text/html"];
NSString *URLtoCall = #"API name as you have";
[manager POST:URLtoCall parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
[formData appendPartWithFileData:imageToUpload name:#"image" fileName:#"temp.jpeg" mimeType:#"image/jpeg"];
} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
}];

Related

How to send image with parameter in AfNetworking

i am sending it with parameter but no working and in Postman Itis working see screenshot below
NSDictionary*Param=#{#"api_token":#"6fkgRh72y6L8DJi1zgYJr55zA0l3vrgnUOU3w6qFDCgX6e0QzwPLwT5D8nOHs8Ye35kFCjrAzSDNYvSsvkxJrmnMxX4iO5GXo7bgjcyKaidhmZ9SqWDEyspnsEFTFjnAX0V80FeJYZ6w8IdOpjoGNO"
};
NSData *imageData = UIImagePNGRepresentation(image);
NSString*url=[NSString stringWithFormat:#"http://asinfrastructure.com/mazad/public/api/v1/user/auction/media/upload/photo"];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager.requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[manager POST:url parameters:Param constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:imageData
name:#"photo"
fileName:#"Image.png" mimeType:#"image/jpeg"];
} progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
NSLog(#"Response: %#", responseObject);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(#"Error: %#", error);
NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:(NSData *)error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] options:NSJSONReadingAllowFragments error:&error];
NSLog(#"%#",JSON);
}];
Your code Works well.
-(void)uploadImage1:(UIImage *)img Dictionary:(NSMutableDictionary *)dictParam {
NSData *imageData = UIImageJPEGRepresentation(img, 0.7);
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager.requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[manager POST:kWOJSignUPCall parameters:dictParam constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
if (imageData != nil) {
[formData appendPartWithFileData:imageData
name:#"profile_image"
fileName:#"user_image.jpg"
mimeType:#"image/jpg"];
}
} progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
NSLog(#"Response: %#", responseObject);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(#"Error: %#", error);
NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:(NSData *)error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] options:NSJSONReadingAllowFragments error:&error];
NSLog(#"%#",JSON);
}];
}
OR Try This.
-(void)uploadImage1:(UIImage *)img Dictionary:(NSMutableDictionary *)dictParam {
NSData *imageData;
if (img == nil) {
}
else {
imageData = UIImageJPEGRepresentation(img, 0.7);
}
AFHTTPRequestSerializer *requestSerializer = [AFHTTPRequestSerializer serializer];
AFHTTPResponseSerializer *responseSerializer = [AFHTTPResponseSerializer serializer];
requestSerializer = [AFJSONRequestSerializer serializer];
responseSerializer = [AFJSONResponseSerializer serializer];
NSError *__autoreleasing* error = NULL;
NSMutableURLRequest *request = [requestSerializer multipartFormRequestWithMethod:#"POST" URLString:kWOJSignUPCall parameters:dictParam constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
if (imageData != nil) {
[formData appendPartWithFileData:imageData
name:#"profile_image"
fileName:#"user_image.jpg"
mimeType:#"image/jpg"];
}
} error:(NSError *__autoreleasing *)error];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
manager.responseSerializer = responseSerializer;
NSURLSessionUploadTask *uploadTask;
uploadTask = [manager uploadTaskWithStreamedRequest:request progress:^(NSProgress * _Nonnull uploadProgress) {
}
completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (error) {
NSLog(#"ERROR WHILE UPLOADING IMAGE = %#",error.localizedDescription);
}
else {
if ([[responseObject valueForKey:#"status"] intValue] == 1) {
NSLog(#"Image Upload Done.");
}
else {
NSLog(#"Image Upload Fails.");
}
}
}];
[uploadTask resume];
}

How to send image as parameters (param) with POST with AFNetworking

I need to send image as param like
URl : some API
params : {profileImage:string(file)}
Means in param list only i have to send image file as string.
i used the below code. but it is not working.
NSData *dataImage = [[NSData alloc] init];
dataImage = UIImagePNGRepresentation(selectedImage);
NSString *stringImage = [dataImage base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
NSDictionary *params = {profileImage : stringImage}
NSString *url = [NetworkRoutes postProfileImageAPIWithMobileNumber:[PTUserDetails getMobileNumber]];
self.operationManager = [AFHTTPSessionManager manager];
self.operationManager.responseSerializer = [AFJSONResponseSerializer serializer]; //
[self.operationManager.requestSerializer setAuthorizationHeaderFieldWithUsername:#“userName” password:#“some password”];
[self.operationManager POST:url parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
NSError *error;
if (![formData appendPartWithFileURL:[NSURL fileURLWithPath:path] name:#"file" fileName:[path lastPathComponent] mimeType:#"image/jpg" error:&error]) {
NSLog(#"error appending part: %#", error);
}
} progress:^(NSProgress * _Nonnull uploadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
}];
your answer no need to be in afnetworking , can also be in nsurlconnection
I am getting resposne
{
response :"Please upload image file"
}
OR
Suggest me how to do like in the attached screen shot . In post man i am getting response
NSData *imgData = UIImageJPEGRepresentation(image, 1.0);
NSUInteger fileSize = [imgData length];
if(fileSize>400000)
{
float size = (float)((float)400000/(float)fileSize);
imgData = [NSData dataWithData:UIImageJPEGRepresentation(image, size)];
}
NSString *imgProfilePic = [imgData base64Encoding];
and then you can send this imgProfilePic to Webservice
If you send your image in multipart then this might be helpful and easiest way than BASE64
and also no need to convert your image into BASE64 String.
- (void)uploadImage:(UIImage*)image withParams:(NSDictionary*)paramsDict withURL:(NSString *)URL
{
NSData *imageData = UIImageJPEGRepresentation(image, 1.0);
AFHTTPRequestOperationManager *manager =
[AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager POST:URL parameters:paramsDict constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
if (imageData!=nil) {
[formData appendPartWithFileData:imageData name:#"imagename" fileName:#"filename" mimeType:#"image/jpeg"];
}
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"success = %#", responseObject);
[appDelegate dismissLoading];
if ([[responseObject valueForKey:#"code"] isEqualToString:#"200"])
{
// code after success
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
[appDelegate dismissLoading];
NSLog(#"error = %#", error);
}];
}
Try to send like following (one of the below) way:
1.
-(void)uploadimage{
AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:#"http://your server.url"]];
NSData *imageData = UIImageJPEGRepresentation(self.avatarView.image, 0.5);
// if you want to pass another parameter with image then
NSDictionary *param = #{#"username": self.username, #"password" : self.password};
AFHTTPRequestOperation *operation = [manager POST:#"rest.of.url" parameters:param constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
//do not put image inside parameters dictionary, but append it!
[formData appendPartWithFileData:imageData name:paramNameForImage 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);
}];
[operation start];
}
2.
UIImage *image = [UIImage imageNamed:#"imageName.png"];
NSData *imageData = UIImageJPEGRepresentation(image,1);
NSString *queryStringss = [NSString stringWithFormat:#"http://your server/uploadfile/"];
queryStringss = [queryStringss stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"text/html"];
[manager POST:queryStringss parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
{
[formData appendPartWithFileData:imageData name:#"fileName" fileName:#"imageName.png" mimeType:#"image/jpeg"];
}
success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSDictionary *dict = [responseObject objectForKey:#"Result"];
NSLog(#"Success: %# ***** %#", operation.responseString, responseObject);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
NSLog(#"Error: %# ***** %#", operation.responseString, error);
}];

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 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

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