Uploading video file to server from iPhone - iphone

I know how to upload images to a server running PHP, but I am stuck on uploading video.
I have used this advice to upload my video file.
Posting method is all ok. What I get on the server is a file of 0 bytes.
My code is below:
- (void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary *)info {
NSURL *videoURL = [info objectForKey:UIImagePickerControllerMediaURL];
NSData *videoData = [NSData dataWithContentsOfFile:[videoURL path]];
}
This videoData is passed in my POST method.
What should I do instead?

for posting video you need to use this function after image picker delegate
- (NSData *)generatePostDataForData:(NSData *)uploadData
{
// Generate the post header:
NSString *post = [NSString stringWithCString:"--AaB03x\r\nContent-Disposition: form-data; name=\"upload[file]\"; filename=\"somefile\"\r\nContent-Type: application/octet-stream\r\nContent-Transfer-Encoding: binary\r\n\r\n" encoding:NSASCIIStringEncoding];
// Get the post header int ASCII format:
NSData *postHeaderData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
// Generate the mutable data variable:
NSMutableData *postData = [[NSMutableData alloc] initWithLength:[postHeaderData length] ];
[postData setData:postHeaderData];
// Add the image:
[postData appendData: uploadData];
// Add the closing boundry:
[postData appendData: [#"\r\n--AaB03x--" dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]];
// Return the post data:
return postData;
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
//assign the mediatype to a string
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
//check the media type string so we can determine if its a video
if ([mediaType isEqualToString:#"public.movie"]){
NSLog(#"got a movie");
NSURL *videoURL = [info objectForKey:UIImagePickerControllerMediaURL];
NSData *webData = [NSData dataWithContentsOfURL:videoURL];
[self post:webData];
[webData release];
}
for post video use this function
- (void)post:(NSData *)fileData
{
NSLog(#"POSTING");
// Generate the postdata:
NSData *postData = [self generatePostDataForData: fileData];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
// Setup the request:
NSMutableURLRequest *uploadRequest = [[[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"http://www.example.com:3000/"] cachePolicy: NSURLRequestReloadIgnoringLocalCacheData timeoutInterval: 30 ] autorelease];
[uploadRequest setHTTPMethod:#"POST"];
[uploadRequest setValue:postLength forHTTPHeaderField:#"Content-Length"];
[uploadRequest setValue:#"multipart/form-data; boundary=AaB03x" forHTTPHeaderField:#"Content-Type"];
[uploadRequest setHTTPBody:postData];
// Execute the reqest:
NSURLConnection *conn=[[NSURLConnection alloc] initWithRequest:uploadRequest delegate:self];
if (conn)
{
// Connection succeeded (even if a 404 or other non-200 range was returned).
NSLog(#"sucess");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Got Server Response" message:#"Success" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
}
else
{
// Connection failed (cannot reach server).
NSLog(#"fail");
}
}

Related

Uploading image to server with base64 haxcode with userid parameter in iPhone

I'm using this code but problem is that it encodes the Haxcode in nsdata conversion block I want to send same has code which I'm getting with userid which is fixed integer. Please help.
NSData *imageData = [NSData dataWithData:UIImageJPEGRepresentation(image1, 0)];
//image.image=image1;
[Base64 initialize];
NSString *b64EncStr = [Base64 encode:imageData];
NSLog(#"encoded.%#",b64EncStr);
NSURL *url = [[NSURL alloc] initWithString:updateimageURL];
NSMutableURLRequest *req = [[NSMutableURLRequest alloc]initWithURL:url];
[req setHTTPMethod:#"POST"];
NSString *trimmed = [b64EncStr stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
paramDataString = [NSString stringWithFormat:#"Id=%d&FromString=%#",100,trimmed];
NSLog(#"%#",paramDataString);
NSData* aData = [paramDataString dataUsingEncoding:NSUTF8StringEncoding];
[req setHTTPBody: aData];
NSURLConnection *theConnection=[[NSURLConnection alloc]initWithRequest:req delegate:self];
if (theConnection)
{
NSMutableData *data = [[NSMutableData alloc] init];
self.receivedData=data;
[data release];
}
else {
UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:nil message:#"Check your networking configuration." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
[alertView release];
}
[url release];
[req release];
It is making the URL connection in right way but response is server error.
First Convert UImage to NSData and from NSData to base64string and then pass that to your Webservice
finalImagePath = [imageData base64EncodedString];
NSString *strImageData = [finalImagePath stringByReplacingOccurrencesOfString:#"+" withString:#"%2B"];
and then send strImageData to your webserivce.
While retriving from server use
NSString *strImageData = [finalImagePath stringByReplacingOccurrencesOfString:#"%2B" withString:#"+"];
Upload base64 string directly to your server
paramDataString = [NSString stringWithFormat:#"Id=%d&FromString=%#",100,b64EncStr];

Http Post Request With Parameters

I have a simple asp.net web service which returns json format data. I want to send http post request with parameter for getting json data. How can I send request and get data ?
post request:
POST /JsonWS.asmx/FirmaGetir HTTP/1.1
Host: localhost
Content-Type: application/x-www-form-urlencoded
Content-Length: length
firID=string
answer:
HTTP/1.1 200 OK
Content-Type: text/xml; charset=utf-8
Content-Length: length
<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://tempuri.org/">string</string>
I'm trying some codes but they didn't work.
NSString *firmadi =#"";
NSMutableData *response;
-(IBAction)buttonClick:(id)sender
{
NSString *firid = [NSString stringWithFormat:#"800"];
response = [[NSMutableData data] retain];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://192.168.1.23/testService/JsonWS.asmx?op=FirmaGetir"]];
NSString *params = [[NSString alloc] initWithFormat:#"firID=%#",firid];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if(theConnection)
{
response = [[NSMutableData data] retain];
}
else
{
NSLog(#"theConnection is null");
}
}
-(void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse*)responsed
{
[response setLength:0];
NSURLResponse * httpResponse;
httpResponse = (NSURLResponse *) responsed;
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data
{
[response appendData:data];
//NSLog(#"webdata: %#", data);
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError*)error
{
NSLog(#"error with the connection");
[connection release];
[response release];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
response = [[NSMutableData data] retain];
NSString *responseString = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSLog(#"%#",responseString);
}
What are you doing here:
[[NSURLConnection alloc] initWithRequest:request delegate:self];
This line returns a NSURLConnection but you are not storing it. This is doing nothing for you.
You are clearing your data before you read it:
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
response = [[NSMutableData data] retain]; // This line is clearing your data get rid of it
NSString *responseString = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSLog(#"%#",responseString);
}
Edit
-(IBAction)buttonClick:(id)sender {
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://192.168.1.23/testService/JsonWS.asmx?op=FirmaGetir"]
cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
timeoutInterval:15];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:[#"firID=800" dataUsingEncoding:NSUTF8StringEncoding]];
self.connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[self.connection start];
}
#pragma NSURLConnection Delegates
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
if (!self.receivedData){
self.receivedData = [NSMutableData data];
}
[self.receivedData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *responseString = [[NSString alloc] initWithData:self.receivedData encoding:NSUTF8StringEncoding];
NSLog(#"%#",responseString);
}
I suffered this problem this morning and I just figure it out now. I guess the key to your question is How to use POST method with parameter. Actually, it is quite simple.
(1) First, you should make sure your file is ready to send. Here we say it is an NSString called stringReady. We use it as a parameter in our method called postRequest (Here is not the HTTP POST parameter we want to talk about. Don't worry).
// Send JSON to server
- (void) postRequest:(NSString *)stringReady{
// Create a new NSMutableURLRequest
NSMutableURLRequest *req = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"http://www.xxxxxx.io/addcpd.php"]];
[req setHTTPMethod:#"POST"];
(2) Now, we say it the parameter that the server wants to get is called "data", this is the way how to insert your parameter to the HTTP body.
// Add the [data] parameter
NSString *bodyWithPara = [NSString stringWithFormat:#"data=%#",stringReady];
See, it's how you add a parameter when using POST method. You just simply put the parameter before the file that you want to send. If you aleary konw what your parameter then you may better to check this website:
https://www.hurl.it/
This will help you to test if you are sending files properly and it will show the response at the bottom of the website.
(3) Third, we pack our NSString to NSData and sent it to server.
// Convert the String to NSData
NSData *postData = [bodyWithPara dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
// Set the content length and http body
NSString *postLength = [NSString stringWithFormat:#"%lu",(unsigned long)[postData length]];
[req addValue:postLength forHTTPHeaderField:#"Content-Length"];
[req setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[req setHTTPBody:postData];
// Create an NSURLSession
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:req
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
// Do something with response data here - convert to JSON, check if error exists, etc....
if (!data) {
NSLog(#"No data returned from the sever, error occured: %#", error);
return;
}
NSLog(#"got the NSData fine. here it is...\n%#\n", data);
NSLog(#"next step, deserialising");
NSError *deserr;
NSDictionary *responseDict = [NSJSONSerialization
JSONObjectWithData:data
options:kNilOptions
error:&deserr];
NSLog(#"so, here's the responseDict\n\n\n%#\n\n\n", responseDict);
}];
[task resume];}
Hope this can help somebody who gets stuck at here.

how to send user name and password using post to server in iphone app

I am making a lo-gin app i want to send the username and password to server for validation how to do this i have done in many ways but i am unable to post.
I am posting the username and password but it did not work if i direct give username and password to php it works so how to do this in iphone to send through post
NSString *post = [[NSString alloc] initWithFormat:#"UserName=%#&Password=%#",username,pass];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSURL *url = [NSURL URLWithString:#"http://www.celeritas-solutions.com/emrapp/connect.php?"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
[theRequest setHTTPMethod:#"POST"];
theRequest setValue:postLength forHTTPHeaderField:#"Content-Length"];
[theRequest setHTTPBody:postData];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if( theConnection )
{
webData = [[NSMutableData data] retain];
}
else
{
NSLog(#"Inside the else condition");
}
[nameInput resignFirstResponder];
[passInput resignFirstResponder];
nameInput.text = nil;
passInput.text = nil;
//Edited your code try this may help you.
NSString *post = [[NSString alloc] initWithFormat:#"UserName=%#&Password=%#",username,pass];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSURL *url = [NSURL URLWithString:#"http://www.celeritas-solutions.com/emrapp/connect.php?"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
[theRequest setHTTPMethod:#"POST"];
[theRequest setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
theRequest setValue:postLength forHTTPHeaderField:#"Content-Length"];
[theRequest setHTTPBody:postData];
//when the user clicks login<action>
- (IBAction)signinClicked:(id)sender {
NSInteger success = 0;
#try {
//to check if username and password feild are filled
if([[self.txtUsername text] isEqualToString:#""] || [[self.txtPassword text] isEqualToString:#""] ) {
[self alertStatus:#"Please enter Username and Password" :#"Sign in Failed!" :0];
} else {
NSString *post =[[NSString alloc] initWithFormat:#"username=%#&password=%#",[self.txtUsername text],[self.txtPassword text]];
NSLog(#"PostData: %#",post);
//post it to your url where your php file is saved for login
NSURL *url=[NSURL URLWithString:#"http://xyz.rohandevelopment.com/new.php"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
//[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[url host]];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(#"Response code: %ld", (long)[response statusCode]);
if ([response statusCode] >= 200 && [response statusCode] < 300)
{
NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"Response ==> %#", responseData);
NSError *error = nil;
NSDictionary *jsonData = [NSJSONSerialization
JSONObjectWithData:urlData
options:NSJSONReadingMutableContainers
error:&error];
success = [jsonData[#"success"] integerValue];
NSLog(#"Success: %ld",(long)success);
if(success == 1)
{
NSLog(#"Login SUCCESS");
} else {
NSString *error_msg = (NSString *) jsonData[#"error_message"];
[self alertStatus:error_msg :#"Sign in Failed!" :0];
}
} else {
//if (error) NSLog(#"Error: %#", error);
[self alertStatus:#"Please Check Your Connection" :#"Sign in Failed!" :0];
}
}
}
#catch (NSException * e) {
NSLog(#"Exception: %#", e);
[self alertStatus:#"Sign in Failed." :#"Error!" :0];
}
if (success) {
[self performSegueWithIdentifier:#"login_success" sender:self];
}
}
- (void) alertStatus:(NSString *)msg :(NSString *)title :(int) tag
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title
message:msg
delegate:self
cancelButtonTitle:#"Ok"
otherButtonTitles:nil, nil];
alertView.tag = tag;
[alertView show];
}
Add Following Code After
[theRequest setHTTPBody:postData];
NSURLResponse *response;// = [[NSURLResponse alloc] init];
NSError *error;// = [[NSError alloc] init;
NSData *urlData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *str=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"Login response: is %#",str);

Uploading video file to the URL

I am trying to upload video file to the specified URL. When I press button video file should upload into the URL which I used. But no response is coming.
NSString *filePath = [[NSBundle mainBundle]pathForResource:#"3idiots" ofType:#"mov"];
NSURL *uploadurl=[NSURL URLWithString:#"http://115.111.27.206:8081/vblo/upload.jsp"];
//NSData *postVideoData = [NSData dataWithContentsOfFile:filePath];
NSData *postVideoData = [string dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postVideoLength = [NSString stringWithFormat:#"%d", [postVideoData length]];
NSMutableURLRequest *request12 = [[[NSMutableURLRequest alloc] init] autorelease];
[request12 setURL:uploadurl];
[request12 setHTTPMethod:#"POST"];
[request12 setValue:postVideoLength forHTTPHeaderField:#"Content-Length"];
[request12 setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request12 setHTTPBody:postVideoData];
NSURLConnection *theConnection12 = [[NSURLConnection alloc] initWithRequest:request12 delegate:self];
if( theConnection12 )
{
webData12 = [[NSMutableData data] retain];
}
else
{
}
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[webData12 setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[webData12 appendData:data];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *loginStatus12 = [[NSString alloc] initWithBytes: [webData12 mutableBytes] length:[webData12 length] encoding:NSUTF8StringEncoding];
NSLog(loginStatus12);
if(loginStatus12)
{
UIAlertView *statusAlert12 = [[UIAlertView alloc]initWithTitle:nil message:(NSString *)loginStatus12 delegate:self cancelButtonTitle:#"cancel" otherButtonTitles:nil];
[statusAlert12 show];
}
}
you need to send the request, add this line after you set the HTTPBody
NSData *serverReply = [NSURLConnection sendSynchronousRequest: request12 returningResponse:&response error:&error];

Uploading Video with iPhone

Is it possible to upload video to a server? I know that images are possible.
If someone can just point me in the right direction that would be awesome.
Thanks
Edited Aug 2015
This answer is now seriously out of date. At the time of writing there weren't to many options and videos were relatively small in size.
If you are looking at doing this now, I would use AFNetworking which makes this much simpler. It will stream the upload from file rather than holding it all in memory, and also supports the new Apple background upload Task.
Docs here: https://github.com/AFNetworking/AFNetworking#creating-an-upload-task
--
Yes this is possible and this is how i went about it.
Implement the following function which runs when the media picker is finished.
- (NSData *)generatePostDataForData:(NSData *)uploadData
{
// Generate the post header:
NSString *post = [NSString stringWithCString:"--AaB03x\r\nContent-Disposition: form-data; name=\"upload[file]\"; filename=\"somefile\"\r\nContent-Type: application/octet-stream\r\nContent-Transfer-Encoding: binary\r\n\r\n" encoding:NSASCIIStringEncoding];
// Get the post header int ASCII format:
NSData *postHeaderData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
// Generate the mutable data variable:
NSMutableData *postData = [[NSMutableData alloc] initWithLength:[postHeaderData length] ];
[postData setData:postHeaderData];
// Add the image:
[postData appendData: uploadData];
// Add the closing boundry:
[postData appendData: [#"\r\n--AaB03x--" dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]];
// Return the post data:
return postData;
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
//assign the mediatype to a string
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
//check the media type string so we can determine if its a video
if ([mediaType isEqualToString:#"public.movie"]){
NSLog(#"got a movie");
NSURL *videoURL = [info objectForKey:UIImagePickerControllerMediaURL];
NSData *webData = [NSData dataWithContentsOfURL:videoURL];
[self post:webData];
[webData release];
}
for the post function i had something like this which i got from somewhere else (sorry i dont know where i found it):
- (void)post:(NSData *)fileData
{
NSLog(#"POSTING");
// Generate the postdata:
NSData *postData = [self generatePostDataForData: fileData];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
// Setup the request:
NSMutableURLRequest *uploadRequest = [[[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"http://www.example.com:3000/"] cachePolicy: NSURLRequestReloadIgnoringLocalCacheData timeoutInterval: 30 ] autorelease];
[uploadRequest setHTTPMethod:#"POST"];
[uploadRequest setValue:postLength forHTTPHeaderField:#"Content-Length"];
[uploadRequest setValue:#"multipart/form-data; boundary=AaB03x" forHTTPHeaderField:#"Content-Type"];
[uploadRequest setHTTPBody:postData];
// Execute the reqest:
NSURLConnection *conn=[[NSURLConnection alloc] initWithRequest:uploadRequest delegate:self];
if (conn)
{
// Connection succeeded (even if a 404 or other non-200 range was returned).
NSLog(#"sucess");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Got Server Response" message:#"Success" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
}
else
{
// Connection failed (cannot reach server).
NSLog(#"fail");
}
}
The above snippet builds the http post request and submits it. You will need to modify it if you want decent error handling and consider using a library that allows async upload (theres one on github)
Also Notice the port :3000 on the server url above, I found it easy for bug testing to start a rails server on its default port 3000 in development mode so i could see the request parameters for debugging purposes
Hope this helps
Since iOS8 there is no need to use 3rd party libraries and you can stream video directly from the file which solves crucial OUT OF MEMORY ERROR when you try to upload bigger videos while loading them from file:
// If video was returned by UIImagePicker ...
NSURL *videoUrl = [_videoDictionary objectForKey:UIImagePickerControllerMediaURL];
NSMutableURLRequest *request =[[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:VIDEO_UPLOAD_LINK]];
[request addValue:#"video" forHTTPHeaderField: #"Content-Type"];
[request setHTTPMethod:#"POST"];
NSInputStream *inputStream = [[NSInputStream alloc] initWithFileAtPath:[videoUrl path]];
[request setHTTPBodyStream:inputStream];
self.uploadConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
iOS7 also offers great NSURLSeession / NSURLSessionUploadTask combo solution, which not only let's you stream directly from the file, but can also delegate task to the iOS process, which will let upload to finish even when your app is closed.
It requires a bit more coding and I have no time to write it all here (you can Google it).
Here are the most crucial parts:
Confugure audio session in background support:
-(NSURLSession *)urlSession{
if (!_urlSession) {
NSDictionary *infoDict = [[NSBundle mainBundle] infoDictionary];
NSString *bundleId = infoDict[#"CFBundleIdentifier"];
NSString *label = [NSString stringWithFormat:#"ATLoggerUploadManager_%#", bundleId];
NSURLSessionConfiguration *conf = (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_7_1) ? [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:label] : [NSURLSessionConfiguration backgroundSessionConfiguration:label];
conf.allowsCellularAccess = NO;
_urlSession = [NSURLSession sessionWithConfiguration:conf delegate:self delegateQueue:self.urlSessionQueue];
_urlSession.sessionDescription = #"Upload log files";
}
return _urlSession;
}
Upload task method:
-(NSURLSessionUploadTask *)uploadTaskForFilePath:(NSString *)filePath session:(NSURLSession *)session{
NSFileManager *fm = [NSFileManager defaultManager];
NSError *error = nil;
// Consruct request:
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setHTTPMethod:#"POST"];
NSString *finalUrlString = [self.uploadURL absoluteString];
if (self.uploadUserId) {
[request setValue:self.uploadUserId forHTTPHeaderField:#"X-User-Id"];
finalUrlString = [finalUrlString stringByAppendingFormat:#"?id=%#", self.uploadUserId];
}
[request setURL:[NSURL URLWithString:finalUrlString]];
/*
It looks like this (it only works if you quote the filename):
Content-Disposition: attachment; filename="fname.ext"
*/
NSString *cdh = [NSString stringWithFormat:#"attachment; filename=\"%#\"", [filePath lastPathComponent]];
[request setValue:cdh forHTTPHeaderField:#"Content-Disposition"];
error = nil;
unsigned long fileSize = [[fm attributesOfItemAtPath:filePath error:&error] fileSize];
if (!error) {
NSString *sizeInBytesAsString = [NSString stringWithFormat:#"%lu", fileSize];
[request setValue:sizeInBytesAsString forHTTPHeaderField:#"X-Content-Length"];
}
NSURL *fileUrl = [NSURL fileURLWithPath:filePath];
NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request fromFile:fileUrl];
uploadTask.taskDescription = filePath;
return uploadTask;
}
Upload function:
[self.urlSession getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
NSMutableDictionary *tasks = [NSMutableDictionary new];
int resumed_running_count = 0;
int resumed_not_running_count = 0;
int new_count = 0;
// 1/2. Resume scheduled tasks:
for(NSURLSessionUploadTask *task in uploadTasks) {
//MILogInfo(#"Restored upload task %zu for %#", (unsigned long)task.taskIdentifier, task.originalRequest.URL);
if (task.taskDescription) {
[tasks setObject:task forKey:task.taskDescription];
}
BOOL isRunning = (task.state == NSURLSessionTaskStateRunning);
if (!isRunning) {
resumed_not_running_count++;
}else{
resumed_running_count++;
}
[task resume];
}
// 2/2. Add tasks / files not scheduled yet:
NSString *uploadFilePath = nil;
// already uploading:
if (![tasks valueForKey:uploadFilePath]) {
NSURLSessionUploadTask *uploadTask = [self uploadTaskForFilePath:uploadFilePath session:_urlSession];
new_count++;
[uploadTask resume];
}
}];
Background session requires UIApplecation delegate (AppDelegate callback implemented:
(void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)())completionHandler
{
NSLog(#"Background URL session needs events handled: %#", identifier);
completionHandler();
}
Have a look at the UIImagePickerController.
As of 3.0 you can allow the choose to shoot a video or pick an existing video. According to the docs you're limited to 10min max on the movie though:
http://developer.apple.com/IPhone/library/documentation/UIKit/Reference/UIImagePickerController_Class/UIImagePickerController/UIImagePickerController.html
NSURL *urlvideo = [info objectForKey:UIImagePickerControllerMediaURL];
NSString *urlString=[urlvideo path];
NSLog(#"urlString=%#",urlString);
NSString *str = [NSString stringWithFormat:#"you url of server"];
NSURL *url = [NSURL URLWithString:[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setFile:urlString forKey:#"key foruploadingFile"];
[request setRequestMethod:#"POST"];
[request setDelegate:self];
[request startSynchronous];
NSLog(#"responseStatusCode %i",[request responseStatusCode]);
NSLog(#"responseStatusCode %#",[request responseString]);