Post data without image using Afnetworking - ios

I want to upload user information to the server. It contains user avatar and user profile data. Now the problem is that user does not upload the avatar always so i want to filter the image if user does not upload it so can anyone help me on this?
Right now i am uploading image using this code and it works fine but i want to upload even when the user does not upload the image
AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:BASE_URL]];
NSData *imageData = UIImagePNGRepresentation(image);
[manager POST:url parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:imageData name:#"file" fileName:#"image.png" mimeType:#"image/png"];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Success %#", responseObject);
[Util showAlertDialog: NSLocalizedString(#"Success", nil):NSLocalizedString(#"Upload Successful", nil)];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Failure %#, %#", error, operation.responseString);
[ Util showAlertDialog: NSLocalizedString(#"Failed", nil):NSLocalizedString(#"Upload Failed, Please try again", nil)];
}];

well i solved it myself by sending empty NSData
AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:BASE_URL]];
NSData *imageData;
CGImageRef cgref = [image CGImage];
CIImage *cim = [image CIImage];
if (cim == nil && cgref == NULL)
{
imageData = [[NSData alloc] init];
}else{
imageData = UIImagePNGRepresentation(image);
}
[manager POST:url parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:imageData name:#"file" fileName:#"image.png" mimeType:#"image/png"];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Success %#", responseObject);
[MBProgressHUD hideHUDForView:view animated:YES];
[Util showAlertDialog: NSLocalizedString(#"Success", nil):NSLocalizedString(#"Upload Successful", nil)];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Failure %#, %#", error, operation.responseString);
[MBProgressHUD hideHUDForView:view animated:YES];
[ Util showAlertDialog: NSLocalizedString(#"Failed", nil):NSLocalizedString(#"Upload Failed, Please try again", nil)];
}];

Related

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

How to Upload Multipart data of image in base64 Using afnetworking

I have used the following code but the response which i get is java.lang.NullPointerException & INTERNAL_SERVER_ERROR I tried many different methods but unable to fix it please help in fixing this.
Getting the Image from the Image picker
UIImage *chosenImage = info[UIImagePickerControllerEditedImage];
Profilebackground.image = chosenImage;
[picker dismissViewControllerAnimated:YES completion:NULL];
NSURL *resourceURL;
UIImage *image =[[UIImage alloc] init];
image =[info objectForKey:#"UIImagePickerControllerOriginalImage"];
NSURL *imagePath = [info objectForKey:#"UIImagePickerControllerReferenceURL"];
imageName = [imagePath lastPathComponent];
resourceURL = [info objectForKey:UIImagePickerControllerReferenceURL];
NSString *extensionOFImage =[imageName substringFromIndex:[imageName rangeOfString:#"."].location+1 ];
if ([extensionOFImage isEqualToString:#"JPG"])
{
imageData =UIImageJPEGRepresentation(image, 1.0);
base64 = [imageData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
extension=#"image/jpeg";
}
else
{
imageData = UIImagePNGRepresentation(image);
base64 = [imageData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
extension=#"image/png";
}
int imageSize=imageData.length/1024;
NSLog(#"imageSize--->%d", imageSize);
if (imageName!=nil) {
NSLog(#"imageName--->%#",imageName);
}
else
{
NSLog(#"no image name found");
}
Send the Image to server
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager POST:#"https://blahblahblah.com/uploadProfileImg?userId=1" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
//NSData *pngData = [[NSData alloc] initWithBase64EncodedString:base64 options:1];
[formData appendPartWithFileData:imageData
name:#"key"
fileName:imageName mimeType:extension];
} success:^(NSURLSessionDataTask *task, id responseObject) {
NSLog(#"Response: %#", responseObject);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSHTTPURLResponse *response = (NSHTTPURLResponse *)task.response;
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);
}];
You can just use the appendPartWithFileData:name:fileName:mimeType: method of the AFMultipartFormData class.
For instance:
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager POST:#"https://blahblahblah.com/imageupload" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:imageData
name:#"key name for the image"
fileName:photoName mimeType:#"image/jpeg"];
} success:^(NSURLSessionDataTask *task, id responseObject) {
NSLog(#"Response: %#", responseObject);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(#"Error: %#", error);
}];
Please try the below code in AFNetworking 2.0.3
Hope this will helpful for u
- (void) createNewAccount:(NSString *)nickname accountType:(NSInteger)accountType primaryPhoto:(UIImage *)primaryPhoto
{
// Ensure none of the params are nil, otherwise it'll mess up our dictionary
if (!nickname) nickname = #"";
NSLog(#"Creating new account %#", params);
[self POST:#"accounts" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFormData:[nickname dataUsingEncoding:NSUTF8StringEncoding] name:#"nickname"];
[formData appendPartWithFormData:[NSData dataWithBytes:&accountType length:sizeof(accountType)] name:#"type"];
if (self.accessToken)
[formData appendPartWithFormData:[self.accessToken dataUsingEncoding:NSUTF8StringEncoding] name:#"access_token"];
if (primaryPhoto) {
[formData appendPartWithFileData:UIImageJPEGRepresentation(primaryPhoto, 1.0)
name:#"primary_photo"
fileName:#"image.jpg"
mimeType:#"image/jpeg"];
}
} success:^(NSURLSessionDataTask *task, id responseObject) {
NSLog(#"Created new account successfully");
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(#"Error: couldn't create new account: %#", error);
}];
}
At last I made it work
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager POST:#"https://blahblahblah.com/uploadProfileImg?userId=1" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:imageData
name:#"key"
fileName:imageName mimeType:extension];
} success:^(NSURLSessionDataTask *task, id responseObject) {
NSLog(#"Response: %#", responseObject);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSHTTPURLResponse *response = (NSHTTPURLResponse *)task.response;
NSLog(#"error: %#",error);
NSLog(#"statusCode: %ld", (long)response.statusCode);
NSString* ErrorResponse = [[NSString alloc] initWithData:(NSData *)error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] encoding:NSUTF8StringEncoding];
NSLog(#"Error Response:%#",ErrorResponse);
}];

Loading an Image with AFNetworking 2.0

I'm trying to add a photo to a POST using the AFNetworking 2.0.
This ios App sends a post an a photo to a blog.
I can'f figure out why the images don't load.
Here is what I got so far:
// publish text and image
-(void)publishTextAndImage:(NSString*)resultDisplay and:(NSString*)subject with:(NSString*)nonce
{
imageData = UIImageJPEGRepresentation(selectedImage, 0.7); // create a data object from selected image
NSString *myUUID = [[NSUUID UUID] UUIDString]; // create a UUID
NSString *formatString = [NSString stringWithFormat:#"<img src=\"/wp-content/uploads/%#\"/>",myUUID];
NSString *contentString = [formatString stringByAppendingString:resultDisplay];
NSString *moodString = [NSString stringWithFormat:#"%d",self.moodNumber];
NSDictionary *parameters = #{#"title":subject,
#"content":contentString,
#"status":#"publish",
#"author":#"wordpress",
#"user_password":#"xrayyankee",
#"nonce":nonce,
#"categories":moodString,
#"attachment":#"image/jpeg"};
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager POST:#"http://thrills.it/?json=posts/create_post"
parameters:parameters
constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
{
if (selectedImage)
{
[formData appendPartWithFileData:imageData name:#"photo" fileName:myUUID mimeType:#"image/jpeg"];
}
}
success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSLog(#"JSON: %#", responseObject);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
NSLog(#"Error: %#", error);
}];
}
Thanks a bunch
I use the AFNetworking in this way :
AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:#"http://thrills.it/?json=posts"]];
NSURLRequest *request = [client multipartFormRequestWithMethod:#"POST" path:#"create_post" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
{
if (selectedImage)
{
[formData appendPartWithFileData:imageData name:#"photo" fileName:myUUID mimeType:#"image/jpeg"];
}
} ];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON)
{
NSLog(#"JSON: %#", responseObject);
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
NSLog(#"Error: %#", error);
}];
[operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
float progressValue = (float)((double)totalBytesWritten/(double)totalBytesExpectedToWrite);
NSLog(#"%f", progressValue);
}];
[self.queue addOperation:operation];
.
#property (nonatomic, strong) NSOperationQueue *queue;
My client is created earlier but it's created like that.
I hope that will help.
I got it, the code was fine it was an issue with the naming of the parameters, here it is:
// publish text and image
-(void)publishTextAndImage:(NSString*)resultDisplay and:(NSString*)subject with: (NSString*)nonce
{
imageData = UIImageJPEGRepresentation(selectedImage, 0.7); // create a data object from selected image
NSString *myUUID = [[NSUUID UUID] UUIDString]; // create a UUID
NSString *formatString = [NSString stringWithFormat:#"<img src=\"/wp- content/uploads/%#\"/>",myUUID];
NSString *contentString = [formatString stringByAppendingString:resultDisplay];
NSString *moodString = [NSString stringWithFormat:#"%d",self.moodNumber];
NSDictionary *parameters = #{#"title":subject,
#"content":contentString,
#"status":#"publish",
#"author":#"wordpress",
#"user_password":#"xrayyankee",
#"nonce":nonce,
#"categories":moodString};
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager POST:#"http://thrills.it/?json=posts/create_post"
parameters:parameters
constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
{
if (selectedImage)
{
[formData appendPartWithFileData:imageData name:#"attachment" fileName:myUUID mimeType:#"image/jpeg"];
}
}
success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSLog(#"JSON: %#", responseObject);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
NSLog(#"Error: %#", error);
}];
so basically I removed the "attachment" parameter from the parameters dictionary and changed the name of the appended imageData to #"attachment". it was an issue of wordpress json api being very picky (:

Uploading image with AFNetworking 2.0

I'm banging my head against the wall with this one. I want to select UIImage from library and upload it to server, like on could do with <form action="http://blabla.request.cfm" method="post" enctype="multipart/form-data">. Instead of success I got this error:
error = Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (JSON text did not start with array or object and option to allow fragments not set.) UserInfo=0x145e5d90 {NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}
I tried this way:
-(void)uploadPhoto{
NSString *path = #"http://blabla.request.cfm";
NSData *imageData = UIImageJPEGRepresentation(self.imageView.image, 0.9);
int priv = self.isPrivate ? 1 : 0;
NSDictionary *parameters = #{#"username": self.username, #"password" : self.password, #"private" : #(priv), #"photo" : imageData};
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager POST:path parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
if(self.imageView.image){
[formData appendPartWithFileData:imageData name:#"avatar" fileName:#"avatar.jpg" mimeType:#"image/jpeg"];
}
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"[UploadVC] success = %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"[UploadVC] error = %#", error);
}];
[self blockView:self.view block:YES];
}
but it's not working... server says that there is no file. Not sure if encrypting is wrong, mime type or what?
Tried also this:
[manager POST:path parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"[UploadVC] success = %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"[UploadVC] error = %#", error);
}];
and this:
manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager POST:path parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFormData:imageData name:#"photo"];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"[UploadVC] success = %#", responseObject);
[self blockView:self.view block:NO];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"[UploadVC] error response.object = %#", operation.responseObject);
[self blockView:self.view block:NO];
}];
nothing is working. Hope someone can help, 'cause I'm stuck with it and circling from question to question here on SO
tia
EDIT: new attempt
1) first was multi-part form
2) creating upload task
none of them worked for me, so I'm still trying to cope with that, but cannot see any solution
I'm not sure which part (I think that some details were missing) was responsible, but I did it finally :) here you go:
-(void)uploadPhoto{
AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:#"http://server.url"]];
NSData *imageData = UIImageJPEGRepresentation(self.avatarView.image, 0.5);
NSDictionary *parameters = #{#"username": self.username, #"password" : self.password};
AFHTTPRequestOperation *op = [manager POST:#"rest.of.url" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
//do not put image inside parameters dictionary as I did, 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);
}];
[op start];
}
Works like a charm :)
You can upload an image with AFNetworking using Swift like this...
let compression = 0.5
let imageData = UIImageJPEGRepresentation("image", CGFloat(compression))
if imageData != nil{
var manager = AFHTTPRequestOperationManager()
manager.responseSerializer.acceptableContentTypes = NSSet(array: ["text/html", "application/json"]) as Set<NSObject>
var dictParams = [
"familyId":"10000",
"contentBody" : "Some body content for the test application",
"name" : "the name/title",
"typeOfContent":"photo"
]
let url = "http://...."
manager.POST(url, parameters: dictParams, constructingBodyWithBlock: { (formData: AFMultipartFormData!) -> Void in
//code
formData.appendPartWithFileData(imageData, name: "file", fileName: "filename", mimeType: "image/png")
}, success: { (operation:AFHTTPRequestOperation!, responseObject:AnyObject!) -> Void in
println(responseObject)
}, failure: { (operation:AFHTTPRequestOperation!, error:NSError!) -> Void in
println(error)
})
}
UIImage *image = [UIImage imageNamed:#"decline_clicked.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:#"decline_clicked.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);
}];

Upload image using AFnetworking did not response anything

Here's the problem :
I want to upload image immediately after finish choosing image from imagepicker.
So, I put my code to upload image using afnetworking in imagepicker delegate method.
But it doesn't response anything.
//set the imageview to current image after choosing
profilePic.image = image;
//dismiss the imagepicker
[picker dismissModalViewControllerAnimated:YES];
//start upload image code
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
#"steventi1901", #"username",
UIImagePNGRepresentation(profilePic.image), #"profile_pic",
nil];
AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:updateProfile];
NSData *imageToUpload = UIImagePNGRepresentation(profilePic.image);
NSMutableURLRequest *request = [client multipartFormRequestWithMethod:#"PUT" path:#"" parameters:params
constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
[formData appendPartWithFileData: imageToUpload name:#"file" fileName:#"temp.png" mimeType:#"image/png"];
//NSLog(#"dalem");
}];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *response = [operation responseString];
NSLog(#"response: [%#]",response);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
if([operation.response statusCode] == 403){
NSLog(#"Upload Failed");
return;
}
NSLog(#"error: %#", [operation error]);
}];
[operation start];
//end upload image code
It really didn't response anything so i didn't know if the process fail or success.
Best and Easy way to upload Image using Afnetworking.
Please use below AFNetworking.
pod 'AFNetworking', '~> 2.5.4'
//Create manager
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
//parameters if any
NSMutableDictionary *AddPost = [[NSMutableDictionary alloc]init];
[AddPost setValue:#"Addparma" forKey:#"param"];
NSString * url = [NSString stringWithFormat:#"www.addyourmainurl.com"];;
NSLog(#"AddPost %#",AddPost);
[manager POST:url parameters:[AddPost copy] constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
//add image data one by one
for(int i=0; i<[Array count];i++)
{
UIImage *eachImage = [Array objectAtIndex:i];
NSData *imageData = UIImageJPEGRepresentation(eachImage,0.5);
[formData appendPartWithFileData:imageData name:[NSString stringWithFormat:#"image%d",i] fileName:[NSString stringWithFormat:#"image%d.jpg",i ] mimeType:#"image/jpeg"];
}
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Success: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
have you set the delegate of the picker?
[yourPicker setDelegate:self]

Resources