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);
}];
Related
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);
}];
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);
}];
I had an application in which I am using Afnetnetworking3.0 for web service calls like this.
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager setRequestSerializer:[AFJSONRequestSerializer serializer]];
[manager setResponseSerializer:[AFJSONResponseSerializer serializer]];
NSURL * urlStr = [NSURL URLWithString:path];
NSDictionary *parameters = #{#"ID":#"fdfdfd",#"No":#"1414"};
NSLog(#"%#",parameters);
[manager POST:urlStr.absoluteString
parameters:parameters
progress:nil
success:^(NSURLSessionDataTask *task, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(#"Error: %#", error);
}];
But it is adding some spaces in parameters dictionary and making the URL not found. Can anybody tell me where I am going wrong ?
Try like this :
NSString *Loginurl = [NSString stringWithFormat:#"http://Enter your url here"];
NSDictionary *params = #{
#"ID":#"fdfdfd",
#"No":#"1414"
};
NSLog(#"Sent parameter to server 1 : %#",params);
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
AFSecurityPolicy* policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];
[policy setValidatesDomainName:NO];
[policy setAllowInvalidCertificates:YES];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:#"application/json", #"text/json", #"text/javascript",#"text/html", nil];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:#"application/json",#"text/html",nil];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:#"application/json",#"text/plain",nil];
[manager POST:Loginurl parameters:params progress:nil success:^(NSURLSessionTask *task, id responseObject) {
NSLog(#"Response from server 1 : %#", [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]);
[self getdata:responseObject];
}
failure:^(NSURLSessionTask *operation, NSError *error)
{
NSLog(#"Error: %#", error);
}];
}
-(void)getdata:(NSDictionary*)RegisterData
{
}
check the log Sent parameter to server 1... and check your url is correct or not?
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);
}];}
I am struggling for hours to get AFMultipartFormData to work...
I need to signup a user by sending his info and his picture.
The documentation i have from the back-end developer to achieve this is:
The required parts are: 'registration' with content type 'application/json' and 'pic' with content type image/*
I tried several ways to do this without any success. What is wrong with the code below?
-(void)serverAuthentication {
NSDictionary *jsonDictionary = #{#"clientId":#"someClientId3", #"name":#"Pantelis", #"email":#"someuser#gmail.com", #"password":#"1234567"};
NSData *imageData = UIImageJPEGRepresentation([UIImage imageNamed:#"sampleJohnTsioris"], 0.5);
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDictionary options:0 error:&error];
if (!jsonData) {
NSLog(#"JSON ERROR");
} else {
NSString *JSONString = [[NSString alloc] initWithBytes:[jsonData bytes] length:[jsonData length] encoding:NSUTF8StringEncoding];
NSLog(#"JSON OUTPUT: %#",JSONString);
}
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager.requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[manager POST:#"http://someserver.com/auth/account/email" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFormData:jsonData name:#"registration"];
[formData appendPartWithFileData:imageData name:#"pic" fileName:#"photo.jpg" mimeType:#"image/*"];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"operation=%#",operation);
NSLog(#"Response: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"operation=%#",operation);
NSLog(#"Error: %#", error);
}];
}
The error i get:
Error Domain=com.alamofire.error.serialization.response Code=-1011
"Request failed: unsupported media type (415)"
You can't change the content type of the request. It must be "multipart/form-data".
You need to make sure the "registration" part has a mime type of "application/json".
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager POST:#"http://someserver.com/auth/account/email" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:jsonData name:#"registration" fileName:#"user.json" mimeType:#"application/json"];
[formData appendPartWithFileData:imageData name:#"pic" fileName:#"photo.jpg" mimeType:#"image/jpeg"];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"operation=%#",operation);
NSLog(#"Response: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"operation=%#",operation);
NSLog(#"Error: %#", error);
}];
I found out the solution. As Jeffery Thomas wrote, you can't change the content type of the request, and there was the problem. Specifically, there was no problem at all sending the image but the json object which needed the name "registration" AND the content-type and i couldn't find the proper way to pass both. So, I made up the headers needed to do that (pass the content-type and the name).
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager POST:#"http://vext.dsigned.gr:8080/auth/account/email" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
NSMutableDictionary *headers = [NSMutableDictionary dictionaryWithObjectsAndKeys: #"application/json; charset=UTF-8",#"Content-Type", #"form-data; name=\"registration\"",#"Content-Disposition", nil];
[formData appendPartWithHeaders:headers body:jsonData];
[formData appendPartWithFileData:imageData name:#"pic" fileName:#"avatar.png" mimeType:#"image/png"];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"operation=%#",operation);
NSLog(#"Response: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"operation=%#",operation);
NSLog(#"Error: %#", error);
}];