Can anyone tell me how to upload audio files with the help of AFNetworking on a server in iOS? Is this ok?
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager POST:urlString parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:imageData
name:#"files"
fileName:audio mimeType:#"mp3"];
[formData appendPartWithFormData:[key1 dataUsingEncoding:NSUTF8StringEncoding]
name:#"key1"];
[formData appendPartWithFormData:[key2 dataUsingEncoding:NSUTF8StringEncoding]
name:#"key2"];
// etc.
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Response: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
You can use AFURLSessionManager to make an upload task, here's the way:
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSURL *URL = [NSURL URLWithString:#"http://example.com/upload"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSURL *filePath = [NSURL fileURLWithPath:#"file://path/to/image.png"];
NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:filePath progress:nil completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
if (error) {
NSLog(#"Error: %#", error);
} else {
NSLog(#"Success: %# %#", response, responseObject);
}
}];
[uploadTask resume];
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];
}
I'm sending multiple images to server using AFMultipartFormData using a for loop to fetch one image at a time:
NSString *string = [NSString stringWithFormat:#"%#/API/Upload",BaseURLString];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager setRequestSerializer:[AFHTTPRequestSerializer serializer]];
[manager setResponseSerializer:[AFHTTPResponseSerializer serializer]];
NSError *error;
NSString *mystring = #"noName";
//FOR Loop Start
for(NSData *eachImage in dataStringArray) {
NSURLRequest *request = [manager.requestSerializer multipartFormRequestWithMethod:#"POST" URLString:string parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFormData:eachImage name:#"myImage"];
[formData appendPartWithFormData:[mystring dataUsingEncoding:NSUTF8StringEncoding]
name:#"FileName"];
} error:&error];
NSURLSessionDataTask *task = [manager dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (error) {
NSLog(#"%#", error.localizedDescription);
return;
}
[uploadedImageIDs addObject:[[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]];
}];
[task resume];
}//for end
[self makeJSON:uploadedImageIDs];
But somehow it calls makeJSON method before. As there are multiple images so I need it to call after the uploading is finished for all images.
Network processing will run by asynchronous so you need to count in network completionHanlder for knowing when all task finished. Like this
NSString *string = [NSString stringWithFormat:#"%#/API/Upload",BaseURLString];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager setRequestSerializer:[AFHTTPRequestSerializer serializer]];
[manager setResponseSerializer:[AFHTTPResponseSerializer serializer]];
NSError *error;
NSString *mystring = #"noName";
NSInteger count = 0;
//FOR Loop Start
for(NSData *eachImage in dataStringArray) {
NSURLRequest *request = [manager.requestSerializer multipartFormRequestWithMethod:#"POST" URLString:string parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFormData:eachImage name:#"myImage"];
[formData appendPartWithFormData:[mystring dataUsingEncoding:NSUTF8StringEncoding]
name:#"FileName"];
} error:&error];
NSURLSessionDataTask *task = [manager dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
count++;
if (error) {
NSLog(#"%#", error.localizedDescription);
} else {
[uploadedImageIDs addObject:[[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]];
}
if (count == dataStringArray.count) {
[self makeJSON:uploadedImageIDs];
}
}];
[task resume];
}//for end
I studied with objective C programming . I don't know how to post image from the library to the api json (I took the picture from library use UIImagePickerController) . Thanks!
My json api:
http://i.stack.imgur.com/DLKZG.png
- (IBAction)btnAddBook:(id)sender {
AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:#"http://192.168.1.54"]];
NSData *imageData = UIImageJPEGRepresentation(self.ivPickedImage.image, 1);
NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
[params setValue:self.tfTitle.text forKey:#"title"];
[params setValue:self.tfPrice.text forKey:#"price"];
[params setValue:self.tfProem.text forKey:#"proem"];
[params setValue:#"Vietnamese" forKey:#"language"];
AFHTTPRequestOperation *op = [manager POST:#"/api/books" parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:imageData name:#"file" 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);
}];
[op start];
Please use this below code:
NSDictionary *requestDictionary = [NSDictionary dictionaryWithObjectsAndKeys:abc.text, #"firstkey",xyz.text, #"secondkey" nil];
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:#"POST" URLString:#"YOUR API URL" parameters:requestDictionary constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
{ [formData appendPartWithFileData:imageData name:#"profile_pic" fileName:#"photo.jpg" mimeType:#"image/jpeg"];
}
} error:nil];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSProgress *progress = nil;
NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:&progress completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
NSLog(#"%#", response);
if (error) {
} else {
}
}];
[uploadTask resume];
Hope this helps.
By using AFNetworking multipart request. you can post image as data. here are the completed block of how to post image as multipart using AFNetworking
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:#"POST" URLString:#"http://example.com/upload" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileURL:[NSURL fileURLWithPath:#"file://path/to/image.jpg"] name:#"file" fileName:#"filename.jpg" mimeType:#"image/jpeg" error:nil];
} 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
[progressView setProgress:uploadProgress.fractionCompleted];
});
}
completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (error) {
NSLog(#"Error: %#", error);
} else {
NSLog(#"%# %#", response, responseObject);
}
}];
[uploadTask resume];
AFNetworking
Here your image is not passed as JSON. By using AFNetworking multipart request, all your request parameter passed as JSON and Image/Video that passed as NSData. where NSData is divided in multiple packets.
Thanks
How to post a image using AFNetworking.i am using below code to post an image.but image is not uploading to server.After posting image i am getting this link in result "http://thisisswitch.com:8084/SmartSwitchService/UserImages/69684177-4601-4665-8890-5424e3fbff73.png".
Can anyone tell me what the problem in code ?
Here is my Code:
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:BaseUrl]];
NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:#"POST" path:posturl parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFormData:imgData name:#"image"];
}];
[httpClient registerHTTPOperationClass:[AFHTTPRequestOperation class]];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
NSDictionary *dict = (NSDictionary *)JSON;
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
}];
[operation start];
From the Github read me:
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSURL *URL = [NSURL URLWithString:#"http://example.com/upload"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSURL *filePath = [NSURL fileURLWithPath:#"file://path/to/image.png"];
NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:filePath progress:nil completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
if (error) {
NSLog(#"Error: %#", error);
} else {
NSLog(#"Success: %# %#", response, responseObject);
}
}];
[uploadTask resume];
Here's how I'm doing it (in AFNetworking 2.x):
- (void)requestWithFormData:(void (^)(id <AFMultipartFormData> formData))formBlock
withParams:(NSDictionary *)params
webservicePath:(NSString *)webservicePath
success:(void (^)(AFHTTPRequestOperation *operation, id jsonDictionary))successBlock
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failureBlock
{
// Handle request for file upload
AFHTTPRequestOperation *op = [self.manager POST:webservicePath
parameters:params
constructingBodyWithBlock:formBlock
success:success
failure:failureBlock];
[op start];
}
Then I use it as per the following:
void (^formBlock)(id <AFMultipartFormData> formData) = ^(id <AFMultipartFormData>formData)
{
NSData *data1 = UIImagePNGRepresentation(profileImage);
[formData appendPartWithFileData:data1 name:#"file" fileName:#"picture.png" mimeType:#"image/png"];
};
[networkingUtil requestWithFormData:formBlock
withParams:params
webservicePath:#"myserver.com/upload"
success:successBlock
failure:failureBlock];
Your server should handle the form data and look for file.
I've been looking examples for the new AFNetworking 2.0 to upload images.
But I'm hitting wall and couldn't figure out what's wrong with the code.
So this is the code I used
NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSURL *URL = [NSURL URLWithString:#"http://myserverurl.com"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromData:imageData progress:nil completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
if (error) {
NSLog(#"Error: %#", error);
} else {
NSLog(#"Success: %# %#", response, responseObject);
}
}];
[uploadTask resume];
TIA
I ended up using the multi-part request
UIImage *image = [info valueForKey:UIImagePickerControllerOriginalImage];
NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = #{#"foo": #"bar"};
[manager POST:#"http://example.com/resources.json" parameters:parameters 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);
}];