upload image with multipart/form-data objective C - ios

I'm new iOS developer. I want upload image with multipart/form-data, this is my obj C code, I get it from postman. And the picture are request parameters of API. I test in postman It work fine, but I test in mobile It's not working and get HTTP 500 error, please check it for me. thanks all. picture API request parameters
strURL = [NSString stringWithFormat:#"%#%#",URL,strURL];
NSArray *parameters = #[ #{ #"name": #"imageInfo", #"value": #"{\"user\":{\"userId\":\"165\"},\"description\":\"test description\",\"competitionId\":\"1\",\"speciesId\":\"13\",\"lng\":\"107.9296875\",\"lat\":\"15.83453574122155\",\"locationName\":\"Đại Lãnh, Đại Lộc, Quảng Nam, Vietnam\",\"originalImageName\":\"\"}" },
#{ #"name": #"filenames", #"value": #"{}" },
#{ #"name": #"files", #"fileName": (UIImageJPEGRepresentation(uploadImage, 0.1)) } ];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:strURL] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10.0];
NSString *boundary = #"---011000010111000001101001";
NSDictionary *headers = #{ #"content-type": #"multipart/form-data; boundary=---011000010111000001101001",
#"cache-control": #"no-cache",
#"postman-token": #"463bcf06-08f6-7611-c1fb-13b0dde79c5c"};
NSError *error;
NSMutableString *body = [NSMutableString string];
for (NSDictionary *param in parameters) {
[body appendFormat:#"\r\n--%#\r\n", boundary];
if (param[#"fileName"]) {
[body appendFormat:#"Content-Disposition:form-data; name=\"%#\"; filename=\"%#\"\r\n", param[#"name"], #"yourimage.jpg"];
[body appendFormat:#"Content-Type: image/jpeg\r\n\r\n"];
[body appendFormat:#"%#", param[#"fileName"]];
if (error) {
NSLog(#"%#", error);
}
} else {
[body appendFormat:#"Content-Disposition:form-data; name=\"%#\"\r\n\r\n", param[#"name"]];
[body appendFormat:#"%#", param[#"value"]];
}
}
[body appendFormat:#"\r\n--%#--\r\n", boundary];
NSData *postData = [body dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPMethod:#"POST"];
[request setAllHTTPHeaderFields:headers];
[request setHTTPBody:postData];
NSURLResponse *response;
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
NSLog(#"%#", error);
} else {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
NSLog(#"%#", httpResponse);
}
}];
[dataTask resume];

You can use AFNetworking third party class.
Reference : https://github.com/AFNetworking/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];

Related

How to send Image to amazon s3 server in ios

I am using below code to send image from gallery to amazon server in ios but it is not successful. May i know the format in which it need to send and do i need to pass just the file name or the entire path of the image?
Thanks.
NSDictionary *headers = #{ #"content-type": #"multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW",
#"x-access-token": #"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1c2UxOTAiLCJpc3MiOiJodHRwczovL3d3dy5oY3VlLmNvIiwicGVybWlzc2lvbnMiOiJhdXRoZW50aWNhdGVkIiwidXNlcmlkIjpudWxsLCJpYXQiOjE0ODYyMDczNDB9.ewu2QtoHl1kBSrM1y6yL9Jr58kiGmhCsy2YWoFrE2OU",
#"cache-control": #"no-cache",
};
NSArray *parameters = #[ #{ #"name": #"username", #"fileName": localFilePath} ];
NSString *boundary = #"----WebKitFormBoundary7MA4YWxkTrZu0gW";
NSError *error;
NSMutableString *body = [NSMutableString string];
for (NSDictionary *param in parameters) {
[body appendFormat:#"--%#\r\n", boundary];
if (param[#"fileName"]) {
[body appendFormat:#"Content-Disposition:form-data; name=\"%#\"; filename=\"%#\"\r\n", param[#"name"], param[#"fileName"]];
[body appendFormat:#"Content-Type: %#\r\n\r\n", param[#"contentType"]];
[body appendFormat:#"%#", [NSString stringWithContentsOfFile:param[#"fileName"] encoding:NSUTF8StringEncoding error:&error]];
if (error) {
NSLog(#"%#", error);
}
} else {
[body appendFormat:#"Content-Disposition:form-data; name=\"%#\"\r\n\r\n", param[#"name"]];
[body appendFormat:#"%#", param[#"value"]];
}
}
[body appendFormat:#"\r\n--%#--\r\n", boundary];
NSData *postData = [body dataUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://zambalauploaddev.ap-southeast-1.elasticbeanstalk.com/upload"]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:10.0];
[request setHTTPMethod:#"POST"];
[request setAllHTTPHeaderFields:headers];
[request setHTTPBody:postData];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
NSLog(#"%#", error);
} else {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
NSLog(#"%#", httpResponse);
NSDictionary * responseDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(#"Reponse Dict:%#",responseDict);
}
}];
[dataTask resume];

How to upload image to server with headers in ios

I'm Trying to upload image to server with headers Hope my code is fine but i don't know it cannot upload. My code is
{
NSDictionary *headers = #{ #"content-type":#"multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW",
#"p-auth-token":self.token};
NSString *urlString = [ NSString stringWithFormat:#"http://ica.com/facilitator/server/v1/media"];
UIImage *image= profile_Image;
NSData *imageData = UIImageJPEGRepresentation(image, 0.1);
double my_time = [[NSDate date] timeIntervalSince1970];
NSString *imageName = [NSString stringWithFormat:#"%d",(int)(my_time)];
NSString *string = [NSString stringWithFormat:#"%#%#%#", #"Content-Disposition: form-data; name=\"file\"; filename=\"", imageName, #".jpg\"\r\n\""];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setAllHTTPHeaderFields:headers];
[request setHTTPMethod:#"POST"];
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:string] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
NSURLSession *session = [NSURLSession sharedSession];
[[session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSDictionary *statusDict = [[NSDictionary alloc]init];
statusDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
[SVProgressHUD dismiss];
NSLog(#"Images form server %#", statusDict);
}] resume];
}
Try AFNetworking with below code,
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:#"POST" URLString:#"upload_url" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:data name:#"upload_file_name" fileName:#"somefilename.jpg" mimeType:#"mime_type_of_file"] // you file to upload
} 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 3 - objective c - send data without key [duplicate]

I am trying to make an HTTP PUT request using AFNetworking to create an attachment in a CouchDB server. The server expects a base64 encoded string in the HTTP body. How can I make this request without sending the HTTP body as a key/value pair using AFNetworking?
I began by looking at this method:
- (void)putPath:(NSString *)path
parameters:(NSDictionary *)parameters
success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
But here the parameters are to be of type: NSDictionary. I just want to send a base64 encoded string in the HTTP body but not associated with a key. Can someone point me to the appropriate method to use? Thanks!
Hejazi's answer is simple and should work great.
If, for some reason, you need to be very specific for one request - for example, if you need to override headers, etc. - you can also consider building your own NSURLRequest.
Here's some (untested) sample code:
// Make a request...
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:myURL];
// Generate an NSData from your NSString (see below for link to more info)
NSData *postBody = [NSData base64DataFromString:yourBase64EncodedString];
// Add Content-Length header if your server needs it
unsigned long long postLength = postBody.length;
NSString *contentLength = [NSString stringWithFormat:#"%llu", postLength];
[request addValue:contentLength forHTTPHeaderField:#"Content-Length"];
// This should all look familiar...
[request setHTTPMethod:#"POST"];
[request setHTTPBody:postBody];
AFHTTPRequestOperation *operation = [client HTTPRequestOperationWithRequest:request success:success failure:failure];
[client enqueueHTTPRequestOperation:operation];
The NSData category method base64DataFromString is available here.
You can use multipartFormRequestWithMethod method as following:
NSURLRequest *request = [self multipartFormRequestWithMethod:#"PUT" path:path parameters:parameters constructingBodyWithBlock:^(id <AFMultipartFormData> formData) {
[formData appendString:<yourBase64EncodedString>]
}];
AFHTTPRequestOperation *operation = [client HTTPRequestOperationWithRequest:request success:success failure:failure];
[client enqueueHTTPRequestOperation:operation];
Here you have an example sending a raw json:
NSDictionary *dict = ...
NSError *error;
NSData *dataFromDict = [NSJSONSerialization dataWithJSONObject:dict
options:NSJSONWritingPrettyPrinted
error:&error];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSMutableURLRequest *req = [[AFJSONRequestSerializer serializer] requestWithMethod:#"POST" URLString:YOUR_URL parameters:nil error:nil];
req.timeoutInterval = 30;
[req setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[req setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[req setValue:IF_NEEDED forHTTPHeaderField:#"Authorization"];
[req setHTTPBody:dataFromDict];
[[manager dataTaskWithRequest:req completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (!error) {
NSLog(#"%#", responseObject);
} else {
NSLog(#"Error: %#, %#, %#", error, response, responseObject);
}
}] resume];
NSData *data = someData;
NSMutableURLRequest *requeust = [NSMutableURLRequest requestWithURL:
[NSURL URLWithString:[self getURLWith:urlService]]];
[reqeust setHTTPMethod:#"PUT"];
[reqeust setHTTPBody:data];
[reqeust setValue:#"application/raw" forHTTPHeaderField:#"Content-Type"];
NSURLSessionDataTask *task = [manager uploadTaskWithRequest:requeust fromData:nil progress:^(NSProgress * _Nonnull uploadProgress) {
} completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
}];
[task resume];
I'm using AFNetworking 2.5.3 and create new POST method for AFHTTPRequestOperationManager.
extension AFHTTPRequestOperationManager {
func POST(URLString: String!, rawBody: NSData!, success: ((AFHTTPRequestOperation!, AnyObject!) -> Void)!, failure: ((AFHTTPRequestOperation!, NSError!) -> Void)!) {
let request = NSMutableURLRequest(URL: NSURL(string: URLString, relativeToURL: baseURL)!)
request.HTTPMethod = "POST"
request.HTTPBody = rawBody
let operation = HTTPRequestOperationWithRequest(request, success: success, failure: failure)
operationQueue.addOperation(operation)
}
}
Please use below method.
+(void)callPostWithRawData:(NSDictionary *)dict withURL:(NSString
*)strUrl withToken:(NSString *)strToken withBlock:(dictionary)block
{
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
Please use below method.
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
NSMutableURLRequest *req = [[AFJSONRequestSerializer serializer] requestWithMethod:#"POST" URLString:[NSString stringWithFormat:#"%#/%#",WebserviceUrl,strUrl] parameters:nil error:nil];
req.timeoutInterval= [[[NSUserDefaults standardUserDefaults] valueForKey:#"timeoutInterval"] longValue];
[req setValue:strToken forHTTPHeaderField:#"Authorization"];
[req setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[req setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[req setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
[[manager dataTaskWithRequest:req completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (!error) {
if ([responseObject isKindOfClass:[NSData class]]) {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
if ((long)[httpResponse statusCode]==201) {
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setObject:#"201" forKey:#"Code"];
if ([httpResponse respondsToSelector:#selector(allHeaderFields)]) {
NSDictionary *dictionary = [httpResponse allHeaderFields];
NSLog(#"%#",[dictionary objectForKey:#"Location"]);
[dict setObject:[NSString stringWithFormat:#"%#",[dictionary objectForKey:#"Location"]] forKey:#"Id"];
block(dict);
}
}
else if ((long)[httpResponse statusCode]==200) {
//Leave Hours Calculate
NSDictionary *serializedData = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:nil];
block(serializedData);
}
else{
}
}
else if ([responseObject isKindOfClass:[NSDictionary class]]) {
block(responseObject);
}
} else {
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setObject:ServerResponceError forKey:#"error"];
block(dict);
}
}] resume];
}

How to upload large size of file by using AFNetworking

I'm working on an app in which I need to upload file to some server, and I'm using AFNetworking to upload file.
All work fine except if file size is short like 2mb and if more than this, server respond me error with status code 500 and doesn't upload file.
Here below is code how I am uploading.
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:lang forHTTPHeaderField:#"Accept-Language"];
[request setValue:authVal forHTTPHeaderField:#"authorization"];
[request setValue:[headerParams objectForKey:#"x-file-name"] forHTTPHeaderField:#"x-file-name"];
[request setValue:[headerParams objectForKey:#"x-convert-document"] forHTTPHeaderField:#"x-convert-document"];
[request setValue:[headerParams objectForKey:#"x-source"] forHTTPHeaderField:#"x-source"];
//convert parameters in to json data
if ([params isKindOfClass:[NSDictionary class]]) {
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params
options:NSJSONWritingPrettyPrinted
error:&error];
jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
[request setURL:[NSURL URLWithString:action]];
[request setTimeoutInterval:200.0];
[request setHTTPMethod:#"POST"];
NSMutableData *postBody = [NSMutableData data];
[postBody appendData:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:imageData];
NSLog(#"File size is : %.2f MB",(float)imageData.length/1024.0f/1024.0f);
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSInteger statusCode = [operation.response statusCode];
NSNumber *statusObject = [NSNumber numberWithInteger:statusCode];
successBlock(responseObject, statusObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
}
The line of code [request setHTTPBody:imageData]; is setting NSData of image.
The same thing works on Android and its working fine but they'r using stream, first to write file into Physical path then by using stream to upload. Is this possible by using AFNetworking? or can I achieve this by using other approach too?
Looking for Suggestion.
Thanks
Note :- I have just implemented Image Upload service using AFNetworking 3.0,
-> Here kBaseURL means Base URL of server
->serviceName means Name of Service.
->dictParams means give parameters if needed, otherwise nil.
->image means pass your image.
Note :- This code written in NSObject Class and we have apply in our Project.
+ (void)requestPostUrlWithImage: (NSString *)serviceName parameters:(NSDictionary *)dictParams image:(UIImage *)image success:(void (^)(NSDictionary *responce))success failure:(void (^)(NSError *error))failure {
NSString *strService = [NSString stringWithFormat:#"%#%#",kBaseURL,serviceName];
[SVProgressHUD show];
NSData *fileData = image?UIImageJPEGRepresentation(image, 0.5):nil;
NSError *error;
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:#"POST" URLString:strService parameters:dictParams constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
if(fileData){
[formData appendPartWithFileData:fileData
name:#"image"
fileName:#"img.jpeg"
mimeType:#"multipart/form-data"];
}
} error:&error];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSURLSessionUploadTask *uploadTask;
uploadTask = [manager uploadTaskWithStreamedRequest:request progress:^(NSProgress * _Nonnull uploadProgress) {
NSLog(#"Wrote %f", uploadProgress.fractionCompleted);
}
completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
[SVProgressHUD dismiss];
if (error)
{
failure(error);
}
else
{
NSLog(#"POST Response : %#",responseObject);
success(responseObject);
}
}];
[uploadTask resume];
}
--> Now apply in our project.
UIImage *imgProfile = //Pass your image.
[WebService requestPostUrlWithImage:#"saveImageWithData" parameters:nil image:imgProfile success:^(NSDictionary *responce) {
NSString *check = [NSString stringWithFormat:#"%#",[responce objectForKey:#"status"]];
if ([check isEqualToString: #"1"]) {
//Image Uploaded.
}
else
{
//Failed to Upload.
}
} failure:^(NSError *error) {
//Error
}];

How to Upload video to server from iPhone?

-(IBAction)uploadToServer :(id)sender
{
NSString *str1=[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"intro.mp4"];
NSLog(#"str1=%#",str1);
NSString *escapedUrlString = [str1 stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(#"escapedUrlString=%#",escapedUrlString);
NSURL *videoURL = [NSURL URLWithString:escapedUrlString];
NSLog(#"videoURL=%#",videoURL);
NSData *newdata = [NSData dataWithContentsOfFile:escapedUrlString];
webdata=[NSData dataWithData:newdata];
NSLog(#"webData = %#",webdata);
[self post:webdata];
}
- (void)post:(NSData *)fileData
{
NSData *videoData = fileData;
NSString *urlString = #"http://rompio.com/web_service/web.php?method=upload_video&user_id=4";
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
[request addValue:contentType forHTTPHeaderField:#"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Disposition: form-data; name=\"userfile\"; filename=\".mp4\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:videoData]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"returnString=== %#", returnString);
}
It's easy to do with the AFNetworking library and you can also use it to track the progress of the video upload. You can download AFNetworking library from here.
And for configuring AFnetworking please refer this Link.
And this code will used to send the video on server
NSString *videoURL = [[NSBundle mainBundle] pathForResource:#"myVideo" ofType:#"mov"];
NSData *videoData = [NSData dataWithContentsOfURL:[NSURL fileURLWithPath: videoURL]];
AFHTTPClient *httpClient = [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:#"http://www.example.com"]];
NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:#"POST" path:#"/videoupload.php" parameters:nil constructingBodyWithBlock:^(id <AFMultipartFormData>formData)
{
[formData appendPartWithFileData:videoData name:#"file" fileName:#"myVideo.mov" mimeType:#"video/quicktime"];
}];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest: request];
[operation setUploadProgressBlock:^(NSInteger bytesWritten,long long totalBytesWritten,long long totalBytesExpectedToWrite)
{
NSLog(#"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite);
}];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {NSLog(#"Video Uploaded Successfully");}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {NSLog(#"Error : %#", operation.responseString);}];
[operation start];
Store selected video URL in some variable :
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
if ([mediaType isEqualToString:(NSString *)kUTTypeMovie]) {
selectedVideoURL = info[UIImagePickerControllerMediaURL];
}
}
For latest version of AFNetworking, below code is used.
NSMutableDictionary *dictParams1 = [[NSMutableDictionary alloc]init];
[dictParams1 setObject:userID forKey:"userID"];
[dictParams1 setObject:otherparam forKey: "otherparam_Key"];
NSLog(#"REQUEST URL : ------------------ %#", API_URL);
NSLog(#"PARAMETERS : ------------------ %#", dictParams1);
NSString *strFileName = [NSString stringWithFormat:#"%ld.mov", [[NSDate date] timeIntervalSince1970]];
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:#"POST" URLString:APIAddFeedVideo parameters:dictParams1 constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileURL:selectedVideoURL name:#"videofile" fileName:strFileName mimeType:#"video/mov" error:nil]; // video/quicktime //video/mp4
} 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(#"VIDEO UPLOAD RESPONSE : %# %#", response, responseObject);
}
}];
[uploadTask resume];

Resources