How to send image with parameter in AfNetworking - ios

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

Related

Unable to save picture in SignUp POST request with Afnetworking

I am trying to upload a picture on server with Multiparts using AFNetworking. I have tried to make a simple POST request without Image and it works fine. Now, can say that service URL is absolutely fine and there is no issue with server and I can see that image URL that is saved in document directory is also fine and all the other parameters are fine too, because they all are working with simple request. Can anyone find some error in my code? My Code is:
(void)uploadPicture:(NSMutableDictionary *)param
{
NSString *string=[NSString stringWithFormat:#"%#%#",base_url,#"register"];
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:#"POST" URLString:string parameters:param constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileURL:[NSURL fileURLWithPath:getImagePath] name:#"picture" fileName:getImagePath mimeType:#"image/jpeg" error:nil];
} error:nil];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
AFJSONRequestSerializer *serializer = [AFJSONRequestSerializer serializer];
[serializer setStringEncoding:NSUTF8StringEncoding];
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
});
}
completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (error) {
NSLog(#"Error: %#", error);
} else {
NSLog(#"%# %#", response, responseObject);
NSDictionary *dict= [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
NSDictionary *dic=responseObject;
NSLog(#"");
}
}];
[uploadTask resume];
}
Try this function :
First Solution
Note : You need to customise as per your need
-(void)getResponeseWithURL:(NSString *)url WithParameter:(NSDictionary *)parameter WithImage:(UIImage *)image ImageArray:(NSMutableArray *)arrImage WithImageParameterName:(NSString *)imagename WithCallback:(void(^)(BOOL success, id responseObject))callback {
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:#"POST" URLString:[NSString stringWithFormat:#"%#%#",BASEURL,url] parameters:parameter constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
if (image) {
[formData appendPartWithFileData:UIImageJPEGRepresentation(image, 0.8) name:imagename fileName:#"Image.jpg" mimeType:#"image/jpeg"];
}
else if (arrImage){
int i = 1;
for (UIImage *recipeimage in arrImage) {
// this condition for maintain server side coloum format : ex name , name_2 , name_3
[formData appendPartWithFileData:UIImageJPEGRepresentation(recipeimage, 0.8) name:i == 1 ? imagename : [NSString stringWithFormat:#"%#_%d",imagename,i] fileName:#"Image.jpg" mimeType:#"image/jpeg"];
i++;
}
}
}error:nil];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
NSURLSessionUploadTask *uploadTask;
uploadTask = [manager
uploadTaskWithStreamedRequest:request
progress:^(NSProgress * _Nonnull uploadProgress) {
dispatch_async(dispatch_get_main_queue(), ^{
});
}
completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (error) {
[UtilityClass showAlertWithMessage: #"Please try again" andWithTitle:#"Network Error" WithAlertStyle:AFAlertStyleFailure];
NSLog(#"Error: %#", [[NSString alloc]initWithData:[[error valueForKey:#"userInfo"] valueForKey:#"com.alamofire.serialization.response.error.data"] encoding:NSUTF8StringEncoding]);
[UtilityClass removeActivityIndicator];
callback(NO,nil);
} else {
callback(YES,responseObject);
}
}];
[uploadTask resume];
}
Second
May you have forgot to add ATS in your project plist file so you need to add this .
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
NSString *string=[NSString stringWithFormat:#"%#%#",base_url,#"register"];
#autoreleasepool {
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager POST:strurl
parameters:parameters
constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
NSMutableArray *allKeys = [[imgParameters allKeys] mutableCopy];
for (NSString *key in allKeys) {
id object = [imgParameters objectForKey:key];
int timestamp = [[NSDate date] timeIntervalSince1970];
NSString *str = [[NSString alloc] initWithFormat:#"%d", timestamp];
NSString *ranstrin = [self randomStringWithLength:8];
// if ([key isEqualToString:#"image"]) {
str = [NSString stringWithFormat:#"TestThumb_%d_%#.jpg",
timestamp, ranstrin];
[formData appendPartWithFileData:object
name:key
fileName:str
mimeType:#"image/jpeg"];
}
}
progress:^(NSProgress *_Nonnull uploadProgress) {
}
success:^(NSURLSessionDataTask *_Nonnull task,
id _Nullable responseObject) {
complete(responseObject, nil);
}
failure:^(NSURLSessionDataTask *_Nullable task,
NSError *_Nonnull error) {
complete(nil, 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);
}];

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

AFNetworking upload image using AFHTTPClient

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

AFNetworking Header

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.

Resources