AFNetworking send image as file not as data - ios

Hi server that I'm sending data is expecting image as file(jpg) not as NSData. This code works, but server can't recognize NSData as image. Any thoughts how to solve this?
+ (void)signupWithParameters:(NSDictionary *)parameters
andUserHaveImage:(BOOL)userHaveImage
andImage:(NSData *)image
successBlock:(void (^) (NSDictionary *response))successHandler
errorBlock:(void (^) (NSDictionary *error))errorHandler
{
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager.requestSerializer setValue:#"multipart/form­data" forHTTPHeaderField:#"Content-Type"];
[manager POST:[NSString stringWithFormat:#"%#/api/1.0/customer/sign-up", DEFAULT_URL] parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
if (userHaveImage == YES) {
//
[formData appendPartWithFileData:image name:#"img_profile" fileName:#"profileImage.jpg" mimeType:#"image/jpg"];
[formData appendPartWithFormData:image name:#"img_profile"];
}
} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
successHandler(responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
errorHandler(#{});
}];
}

Solved by converting image to UTF8 string and sending it in that format.

Related

Upload multiple Image or File using AFNetworking,

I want to upload multiple images using AFNetworking.
like this Please Check This Image
i have attached example of the postman.
My Code :
NSString *key = [[mediaInfo allKeys] objectAtIndex:0];
NSDictionary *dict = [[mediaInfo objectForKey:key] objectAtIndex:0];
UIImage *image = [dict objectForKey:IQMediaImage];
NSMutableDictionary *dictParam = [[NSMutableDictionary alloc] init];
[dictParam setValue:imageData forKey:#"Files"];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager POST:#BaseURL(#"/MediaUpload") parameters:dictParam progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { }];
AFNetworking 3.0
Check this method from AFURLSessionManager:
- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request
fromFile:(NSURL *)fileURL
progress:(void (^)(NSProgress *uploadProgress)) uploadProgressBlock
completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler
Full code implementation:
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *sessionManager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
[[sessionManager uploadTaskWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:#BaseURL(#"/MediaUpload")]]
fromFile:[NSURL fileURLWithPath:#"/path/to/uploading_file"]
progress:^(NSProgress * _Nonnull uploadProgress) { }
completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
}] resume];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager.requestSerializer setValue:#"multipart/form­data" forHTTPHeaderField:#"Content-Type"];
[manager POST:[NSString stringWithFormat:#"%#/api/1.0/customer/sign-up", DEFAULT_URL] parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
if (userHaveImage == YES) {
[formData appendPartWithFileData:image name:#"img_profile" fileName:#"profileImage.jpg" mimeType:#"image/jpg"];
[formData appendPartWithFormData:image name:#"img_profile"];
}
Then converting image to UTF8 string and sending it in that format.

Objective-C: How to send a post request with a multidimensional array of type key value

From application, written in Objective (we use AFNetworking), I need to send a POST request, in the body of which - a multidimensional array of the type "key": "value"
We send request this way:
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager.requestSerializer setValue:#“application/json” forHTTPHeaderField:#“Accept”];
[manager.requestSerializer setValue:#“multipart/form-data” forHTTPHeaderField:#“Content-Type”];
[manager POST:url parameters:dict constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
for (UIImage* image in photoArray) {
NSData *dataImage = UIImageJPEGRepresentation(image,1);
[formData appendPartWithFileData:dataImage name:randomString fileName:[NSString stringWithFormat:#“%#.jpeg”,randomString] mimeType:#“image/jpeg”];
}
} progress:^(NSProgress * _Nonnull uploadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(#“!!!!! %#“, responseObject);
if (success) {
[KVNProgress dismiss];
success(responseObject);
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(#“%#“, error.localizedFailureReason);
[KVNProgress showError];
}];
And this way we form NSDictionary:
NSString*name = model.name;
NSString*lat = model.lat;
NSString*lon = model.lon;
NSDictionary* dic = [NSDictionary
dictionaryWithObjectsAndKeys:name,#"name",lat,#"lat",lon,#"lon", nil];
[addressArray addObject:dic];
Here's what we get on Objective
Here is what request the server receives
And here's what should come
How to build an object on Objective so that data [address] came to the HTTP server as indicated in the 3 picture?

app crashing using afhttpsessionmanager 3.0

i tried like this in webservices.m
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.requestSerializer=[AFHTTPRequestSerializer serializer];
manager.responseSerializer=[AFHTTPResponseSerializer serializer];
manager.responseSerializer.acceptableContentTypes =[NSSet setWithObject:#"text/html"];
[manager POST:meetingupdateurlparams parameters:meetingdictparams progress:nil
success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable
responseObject)
{
NSLog(#"Complete");
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull
error)
{
NSLog(#"Fail %#",error);
}];
i call this service in Viewcontroller.m
NSString *updateMeetingurl=#" url ";
NSDictionary *dictparms=#{ params };
[Servicecall meetingupdate:updateMeetingurl meetingupdatedict:dictparms];
[Servicecall setDelegate:self];
but i am getting error like this
-[AFHTTPSessionManager :parameters:progress:success:failure:] unrecognized selector sent to instance 0x792cfcb0'
*** First throw call stack:
so any one can help in this issuance...thanks in advance..
UPDATE:
I now see where you're doing wrong.
POST:meetingupdateurlparams this part.
Shouldn't you use
POST:meetingupdateurl instead?
I'm not sure which version of AFNetworking you're using.
But it seems like the method signature you're using does not exist.
Try POST:parameters:success:failure: instead of POST:parameters:progress:success:failure.
See the documentation.
I got same error.
It's a issue with Xcode,you should clean build folder(or delete your DerivedData folder,Xcode -> Preferences -> Location -> Locations -> Derived Data).Because Xcode didn't fully clean the older AFNetworking.
Try this USing Afnetworking 3
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:#"POST" URLString:#"URL"parameters:#{#"paramter":#""} constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
//if you want to pass image file
if (image) {
[formData appendPartWithFileData:UIImageJPEGRepresentation(image, 0.8) name:imagename fileName:#"Image.jpg" mimeType:#"image/jpeg"];
}
}error:nil];
AFURLSessionManager *managers = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
managers.responseSerializer = [AFJSONResponseSerializer serializer];
NSURLSessionUploadTask *uploadTask;
uploadTask = [managers
uploadTaskWithStreamedRequest:request
progress:^(NSProgress * _Nonnull uploadProgress) {
dispatch_async(dispatch_get_main_queue(), ^{
});
}
completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (error) {
} else {
// here your response
}
}];
[uploadTask resume];

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

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