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);
}];
Related
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];
}
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) {
}];
This is my code to upload the photo using AFNetworking.
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:#"POST" URLString:urlString parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:dataImage name:#"file" fileName:#"Photo" mimeType:#"image/jpeg"];
} 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
NSLog(#"PROGRESS :%.2f", uploadProgress.fractionCompleted);
block(uploadProgress, nil);
});
}
completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (error) {
NSLog(#"Error: %#", error);
} else {
NSLog(#"%# %#", response, responseObject);
}
}];
[uploadTask resume];
But I need to add a header parameter type.
My the header name is "GW-Token"
It returns error because it needs to check if the token is valid.
And the token should be on header
I am using AFNetworking 3.0
THANKS!
Hope this will help:
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager.requestSerializer setValue:[NSString stringWithFormat:#"Bearer %#", [[NSUserDefaults standardUserDefaults] objectForKey:TOKEN]] forHTTPHeaderField:#"Authorization"];
UPDATE:
This is fully implemented code that is working for me:
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager.requestSerializer setValue:[NSString stringWithFormat:#"Bearer %#", [[NSUserDefaults standardUserDefaults] objectForKey:TOKEN]] forHTTPHeaderField:#"Authorization"];
[manager.requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[manager.requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[manager POST:[NSString stringWithFormat:#"%#/users/updateProfile", DEFAULT_URL] parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:profileImage name:#"file" fileName:[NSString stringWithFormat:#"%#.jpg", imageName] mimeType:#"image/jpeg"];
} progress:nil
success:^(NSURLSessionDataTask *task, id responseObject) {
completionHandler(responseObject);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSData *errorData = error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey];
if (errorData) {
NSDictionary *serializedData = [NSJSONSerialization JSONObjectWithData: errorData options:kNilOptions error:nil];
errorHandler(serializedData);
}else {
NSDictionary *noData = #{#"noData": #"No data!"};
errorHandler(noData);
}
}];
#Yeshua, try following one to set header field.
[request setValue:#"Your GW-Token Value" forHTTPHeaderField:#"GW-Token"];
then serialize request.
I'm trying to post data with x-www-form-urlencoded body.
Posting via postman, it is ok
But i cant do it via afnetworking 3. Here is my code
NSDictionary *parameters = #{#"login" : email,
#"password": password};
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters
options:0
error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
self.requestSerializer = [AFJSONRequestSerializer serializer];
NSString *urlString = [NSString stringWithFormat:#"%#/%#", HTTPBaseRequestURL, appendLoginUrl];
NSLog(#"URL %#\njsonString %#", urlString, jsonString);
[self POST:urlString parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
[formData appendPartWithFormData:jsonData name:#"data"];
} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
onSuccess(responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSString *errorDescription = [NSError serverErrorMessageFromData:(NSData *)error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey]];
NSInteger statusCode = [NSHTTPURLResponse errorCode:(NSHTTPURLResponse*)task.response];
NetworkRequestError *requestError = [[NetworkRequestError alloc] initWithType:
(NSHTTPURLResponse*)task.response ? NetworkRequestErrorTypeServerError : NetworkRequestErrorTypeNoConnection
description:
(NSHTTPURLResponse*)task.response ? errorDescription : nil];
requestError.statusCode = statusCode;
NSLog(#"Error from server: %#, status code = %ld, error type = %lu", requestError.errorDescription, (long)requestError.statusCode, (unsigned long)requestError.type);
onFailure(requestError);
}];
Please, help me to understand how to correctly do this. Thanks!
After commenting I finally found the answer to this. Here's my correctly functioning request now, note the addition of
[manager.requestSerializer setValue:#"application/x-www-form-urlencoded; charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
Here's the full code:
NSString *url = [NSString stringWithFormat:#"%#%#",APIBASE,APIUSERENDPOINT];
NSDictionary* parametersDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
username, #"username",
password, #"password",
nil
];
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc]initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[manager.requestSerializer setValue:#"application/x-www-form-urlencoded; charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
[manager POST:url parameters:parametersDictionary progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(#"%#",responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(#"%#",error);
}];
try append custom header info ,for example:
[self.requestSerializer setValue:#" application/x-www-form-urlencoded; charset=UTF-8" forHTTPHeaderField:#"Content-Type];
hope it help for you.
Here . It worked with me . So easy .
NSDictionary* parametersDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
#"deviceTokenIOS", #"db487c983ebbe7c2fb066d292bb4318175f54ab27b6b9df7871907e1d0ed62ba",
#"message", #"Hello Dunglt",
nil
];
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:#"db487c983ebbe7c2fb066d292bb4318175f54ab27b6b9df7871907e1d0ed62ba", #"deviceTokenIOS", #"Hello Dunglt", #"message", nil];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
[manager POST:[NSURL URLWithString:url].absoluteString parameters:dict progress:nil success:^(NSURLSessionTask *task, id responseObject) {
NSLog(#"%#", responseObject);
}
failure:^(NSURLSessionTask *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];}
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);
}];}