I'm trying to upload an image using AFNetworking library, its a post request, the image should be in the body. i converted it to NSData and tried to send it, but it didn't work, all what I got from the backend guy that the image form should be as image file.
My code is below:
+(void)imageUpload:(NSMutableDictionary *)imageData :(void(^)(BOOL success,NSError *error,NSString *path))block{
NSString *urlString = [baseUrl stringByAppendingString:@"Media/ImageUpload"];
NSMutableDictionary *parameters = [NSMutableDictionary new];
[parameters setObject:[self getXsession] forKey:@"x-session"];
UIImage *image = [imageData objectForKey:@"image"];
NSData *imgData = UIImagePNGRepresentation(image);
NSMutableDictionary *bodyImage = [NSMutableDictionary new];
[bodyImage setObject:imgData forKey:@"image"];
[bodyImage setObject:@"leads_temp" forKey:@"folder"];
[self makePostRequestWithUrl:urlString parameters:parameters body:bodyImage headers:nil updateXsession:NO completionBlock:^(NSError *error, id responseObject) {
BOOL success = [responseObject[@"meta"][@"status"]isEqualToString:@"OK"]?YES:NO;
if(success){
NSString *path = responseObject[@"response"][@"path"];
if (block){
block(success,nil,path);
}
}else {
if (block){
block(NO,error,nil);
}
}
}];
}
Post request:
+(void)makePostRequestWithUrl:(NSString *)url parameters:(NSMutableDictionary *)parameters body:(NSMutableDictionary*)body headers:(NSDictionary *)headers updateXsession:(BOOL)shouldUpdate completionBlock:(void(^)(NSError *error, id responseObject))block {
NSError *error;
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:url parameters:parameters error:&error];
request.timeoutInterval = 30;
NSData *jsonData2 = [NSJSONSerialization dataWithJSONObject:body options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData2 encoding:NSUTF8StringEncoding];
stringWithFormat:@"%@\n%@\n%@",tableValue,jsonString,@"}"];
[request setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[[manager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
NSHTTPURLResponse *myResponse = (NSHTTPURLResponse *)response ;
if (myResponse && shouldUpdate) {
//do some stuffs
}
if (block) {
block(error, responseObject);
}else {
block(responseObject, error);
return ;
}
}]resume];
}
Any idea what the solution could be? thanks.