Tuesday, May 31, 2011

Download video from URL and Save it in iPhone SDK

Hello Friends,

Today we will discuss for downloading video from particular URL and save it to application sandbox. Generally video files are vary large, so we need efficient way to perform such task. I used to follow the following method.

NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setHTTPMethod:@"GET"];
NSError *error;
NSURLResponse *response;

NSString *documentFolderPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *videosFolderPath = [documentFolderPath stringByAppendingPathComponent:@"videos"]; 

Now we need to check that video folder is exist or not. If not, then we will create it.

BOOL isDir;
if (([fileManager fileExistsAtPath:videosFolderPath isDirectory:&isDir] && isDir) == FALSE) {
    [[NSFileManager defaultManager] createDirectoryAtPath:videosFolderPath attributes:nil];
}


NSData *urlData;
NSString *downloadPath = @"http://foo.com/videos/bar.mpeg";
[request setURL:[NSURL URLWithString:downloadPath]];
urlData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *filePath = [videosFolderPath stringByAppendingPathComponent:@"bar.mpeg"];
BOOL written = [urlData writeToFile:filePath atomically:NO];
if (written)
    NSLog(@"Saved to file: %@", filePath);

Have a nice day !!

3 comments:

  1. It is not working the video.It should be saved with mp4 extension in order to be used in iphone app.The rest is okey:)

    ReplyDelete
  2. do u hav sample project for it?

    ReplyDelete
  3. Really Good tips and advises you have just shared. Thank you so much for taking the time to share such a piece of nice information. Looking forward for more views and ideas, Keep up the good work! Visit here for Product Engineering Services | Product Engineering Solutions.

    ReplyDelete