AFNetworking form data uploading issue - ios

I want to POST form data using AFNetworking. I am using this piece of code to achieve this:
// Create service request url
NSString *urlString = [NSString stringWithFormat:#"%#%#", kBaseURL, webServiceAPIName];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager.requestSerializer setValue:#"myUser" forHTTPHeaderField:#"X-User-Agent"];
[manager.requestSerializer setValue:#"multipart/form-data" forHTTPHeaderField:#"Content-Type"];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
// Set calling keys
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setObject:#"5341" forKey:#"Id"];
[dict setObject:#"f1" forKey:#"refDataId"];
[dict setObject:#"f1" forKey:#"customRefDataId"];
[dict setObject:#"587" forKey:#"cost"];
[manager POST:urlString parameters:dict constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:UIImagePNGRepresentation(files[0]) name:#"ImageName" fileName:#"file1" mimeType:#"image/png"];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"upload successful");
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error image upload");
}];
After execution of this block after waiting some time it goes in Failure Section. Logging : "Error image upload". without giving any error.
I tried my API in POSTMAN API CLIENT and there it is working fine.I am able to send data and get response back.
And after running this block i am not able to run any other API call I have to stop my app and run again to run any other API call.
What is the issue with this code why I am not able to upload any form data and Why it block my any other API calls

Try below code:
-(void) uploadImage {
NSString *imagePath = [[NSUserDefaults standardUserDefaults] objectForKey:#"userimage"];
NSString * urlString = [stagingURL stringByReplacingOccurrencesOfString:#"user/" withString:#""];
NSString * uploadURL = #"Your URL where image to be uploaded";
NSLog(#"uploadImageURL: %#", uploadURL);
NSData *imageData = UIImageJPEGRepresentation([UIImage imageWithData:[NSData dataWithContentsOfFile:imagePath]], 0.5);
NSString *queryStringss = [NSString stringWithFormat:#"%#",uploadURL];
queryStringss = [queryStringss stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer=[AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"text/html"];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"text/plain"];
[manager POST:queryStringss parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:imageData name:#"file" fileName:#"file" mimeType:#"image/jpeg"];
}
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Success: %# ***** %#", operation.responseString, responseObject);
[MBProgressHUD hideAllHUDsForView:self.view animated:YES];
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
[MBProgressHUD hideAllHUDsForView:self.view animated:YES];
NSLog(#"Error: %# ***** %#", operation.responseString, error);
}];}

Related

AFNetworking - Make an HTTP POST to REST, sending a JSON with Base64string image

I am trying to send a base64 encoded image among some other strings using http POST and AFNetworking. I am trying to send the parameters as an NSDictionary:
NSMutableDictionary *info = [NSMutableDictionary dictionary];
[info setValue:filedata forKey:#"filedata"];
[info setValue:comments forKey:#"comments"];
[info setValue:username forKey:#"username"];
[info setValue:#"jpg" forKey:#"filetype"];
[info setValue:filename forKey:#"filename"];
and POST using AFNetworking:
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc]initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager.requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[manager POST:#"https://myurl.com/fileupload" parameters:info progress:nil success:^(NSURLSessionTask *task, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(NSURLSessionTask *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
However I am not sure what else to do at this point. What am I missing? Thank you
You can use the following example
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager POST:#"https://myurl.com/fileupload" 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);
}];

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

Imagga.com image recogition /content - Image upload failed with request timed out

I try to upload the image http://api.imagga.com/v1/content but it failed, here the code
AFHTTPRequestOperationManager *taggingManager = [AFHTTPRequestOperationManager manager];
[taggingManager setRequestSerializer:[AFHTTPRequestSerializer serializer]];
[taggingManager.requestSerializer setAuthorizationHeaderFieldWithUsername: #"#" password: #"#"];
NSString *imagePath = [[NSBundle mainBundle]pathForResource:#"apple" ofType:#"jpeg"];
NSData *imageData = [NSData dataWithContentsOfFile:imagePath];
[taggingManager POST:#"http://api.imagga.com/v1/content"
parameters:nil 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);}];
getting this error: Error Domain=NSURLErrorDomain Code=-1001 "The request timed out."
I got help from imagga team, it works well.
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager setRequestSerializer:[AFHTTPRequestSerializer serializer]];
[manager.requestSerializer willChangeValueForKey:#"timeoutInterval"];
[manager.requestSerializer setTimeoutInterval:10]; // 10 sec. timeout for the content upload itself
[manager.requestSerializer didChangeValueForKey:#"timeoutInterval"];
[manager.requestSerializer setAuthorizationHeaderFieldWithUsername:api_key password:api_secret];
[manager POST:#"http://api.imagga.com/v1/content" parameters:nil constructingBodyWithBlock:^(id formData) {
[formData appendPartWithFileData:imageData
name:#"file"
fileName:#"photo.jpg" mimeType:#"image/jpeg"];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Response: %#", responseObject);
NSString *content_id = [[[responseObject valueForKey:#"uploaded"] objectAtIndex:0] valueForKey:#"id"];
NSLog(#"CONTENT ID: %#", content_id);
AFHTTPRequestOperationManager *taggingManager = [AFHTTPRequestOperationManager manager];
[taggingManager setRequestSerializer:[AFHTTPRequestSerializer serializer]];
[taggingManager.requestSerializer willChangeValueForKey:#"timeoutInterval"];
[taggingManager.requestSerializer setTimeoutInterval:10]; // 10 sec. timeout for the tagging itself
[taggingManager.requestSerializer didChangeValueForKey:#"timeoutInterval"];
[taggingManager.requestSerializer setAuthorizationHeaderFieldWithUsername:api_key password:api_secret];
NSLog(#"TAGGING Request for content ID: %#", content_id);
[taggingManager GET:#"http://api.imagga.com/v1/tagging" parameters:#{#"content":content_id}
success:^(AFHTTPRequestOperation *taggingOperation, id taggingResponseObject)
{
NSLog(#"TAGGING Response: %#", taggingResponseObject);
NSArray * tags = [[[taggingResponseObject valueForKey:#"results"] objectAtIndex:0] valueForKey:#"tags"];
for (id entry in tags) {
NSString *tag = [entry valueForKey:#"tag"];
float confidence = [[entry valueForKey:#"confidence"] floatValue];
// ... do something with each tag and its confidence score
}
} failure:^(AFHTTPRequestOperation *taggingOperation, NSError *taggingError) {
NSLog(#"Tagging Error: %#", taggingError);
}];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Upload Error: %#", error);
}];

How to do POST with action key in Objective C using AFNnetworking

I'm trying to do a POST with action parameter called "#load".
To my webservice is a key need to show results: action:#load
How I can do this using AFNetworking framework? Here a sample of my wrong code:
First the constant declaration:
const NSString *BASE_URL = #"http://www.mywebservice.com/request.php";
Now the code:
-(void)requisitarEventos{
[smartEventos removeAllObjects];
NSString* url = [BASE_URL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[SVProgressHUD showWithStatus:#"Loading..." maskType:SVProgressHUDMaskTypeGradient];
NSDictionary *parameters = [NSDictionary dictionaryWithObjectsAndKeys:#"#load",#"action", nil];
[manager POST:url parameters:parameters
success:^(AFHTTPRequestOperation *operation, id responseObject) {
[self carregarEventos:responseObject];
[SVProgressHUD dismiss];
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
[SVProgressHUD dismiss];
}];
}
I found the answer. The real problem of my code that's my Web Service doesn't give results of Content-Type in "application/json", but in "text/html".
I solve the problem using this code below:
NSMutableSet *contentTypes = [[NSMutableSet alloc] initWithSet:manager.responseSerializer.acceptableContentTypes];
[contentTypes addObject:#"text/html"];
manager.responseSerializer.acceptableContentTypes = contentTypes;
And the full code of my class:
-(void)callEvents{
[smartEvents removeAllObjects];
NSString* url = [NSString stringWithFormat:#"%#myService.php?action=load", BASE_URL];
url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[SVProgressHUD showWithStatus:#"Loading..." maskType:SVProgressHUDMaskTypeGradient];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
NSMutableSet *contentTypes = [[NSMutableSet alloc] initWithSet:manager.responseSerializer.acceptableContentTypes];
[contentTypes addObject:#"text/html"];
manager.responseSerializer.acceptableContentTypes = contentTypes;
[manager GET:url parameters:nil
success:^(AFHTTPRequestOperation *operation, id responseObject) {
[self carregarEventos:responseObject];
[SVProgressHUD dismiss];
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
[SVProgressHUD dismiss];
}];
}
please see this , I make a simple post method with callback ,
POST with URL parameters and JSON body in AFNetworking

Resources