27

Playing Youtube video in the app is easy and well documented around.

There are two problems with that:

  1. after closing Youtube player, if user wants to play it again it has to wait for online streaming again
  2. can't play offline (load video at home to watch on the road)

Does anyone have code to:

  1. download Youtube video to documents folder and show progress of download
  2. play downloaded video by loading file from documents folder (meaning even when not connected to the internet)
orftz
  • 1,124
  • 13
  • 22
Biko
  • 305
  • 1
  • 5
  • 11

6 Answers6

42

To download the video from YouTube:

  1. Get the URL to download from, via the YouTube API or whatever other method.
  2. Create an NSOutputStream or NSFileHandle opened on a temporary file (in NSTemporaryDirectory() or a temp-named file in your Documents directory).
  3. Set up your progress bar and whatever else you need to do.
  4. Allocate and start an NSURLConnection to fetch the file from the URL. Do not use sendSynchronousRequest:returningResponse:error:, of course.
  5. In the connection:didReceiveResponse: delegate method, read out the length of data to be downloaded for proper updating of the progress bar.
  6. In the connection:didReceiveData: delegate method, write the data to the output stream/file handle and update the progress bar as necessary.
  7. In connectionDidFinishLoading: or connection:didFailWithError:, close the output stream/file handle and rename or delete the temporary file as appropriate.

To play it back, just use NSURL's fileURLWithPath: to create a URL pointing to the local file in the Documents directory and play it as you would any remote video.

Anomie
  • 86,459
  • 13
  • 122
  • 143
  • Great answer Anomie - I'm going to try it asap. – Biko May 24 '11 at 04:26
  • MiRAGe, got stucked into cleaning code from https://github.com/iosdeveloper/MyTube - decided to see if the mechanism used there is robust. I'll check Anomie solution after that. – Biko Jun 01 '11 at 04:09
  • How can you get the download URL from the Youtube API? – zakdances Jun 18 '12 at 10:10
  • 1
    @yourfriendzak PSYouTubeExtractor can be used for that. there are lot of open-source apps (mentioned in answers below) which does the same. – Tatvamasi Jul 01 '12 at 08:50
  • @Biko #Anomie the chines app you are discussing might be 'ystream' - I am not sure if this approach (directly accessing mp4 url) violate Terms and Conditions (YouTube) ? Also, the method in which url is extracted looked rather raw. Is it robust ? can it be relied up on? – Tatvamasi Jul 01 '12 at 08:52
  • can anyone provide a demo for that? – Sneha Jul 28 '16 at 12:43
7

Ive used classes from this project: https://github.com/larcus94/LBYouTubeView It works fine for me. I can download youtube videos.

I used this code:

LBYouTubeExtractor *extractor = [[[LBYouTubeExtractor alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:(@"http://www.youtube.com/watch?v=%@"), self.videoID ]] quality:LBYouTubeVideoQualityLarge] autorelease];
[extractor extractVideoURLWithCompletionBlock:^(NSURL *videoURL, NSError *error) {
    if(!error) {
        NSLog(@"Did extract video URL using completion block: %@", videoURL);

        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            NSData *data = [NSData dataWithContentsOfURL: videoURL];
            NSString *pathToDocs = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
            NSString *filename = [NSString stringWithFormat:(@"video_%@.mp4"), self.videoID ];
            [data writeToFile:[pathTODocs stringByAppendingPathComponent:filename] atomically:YES];
            NSLog(@"File %@ successfully saved", filename);
        });
    } else {
        NSLog(@"Failed extracting video URL using block due to error:%@", error);
    }
}];

You can show progress of downloading using technique described in the posts above.

Petr
  • 826
  • 1
  • 12
  • 35
6

Here is my example: https://github.com/comonitos/youtube_video

I used PSYouTubeExtractor.h class by Peter Steinberger It can get youtube mp4 video url and than downloading and viewing is not a problem

NSURLConnection + NSNotificationCenter + PSYouTubeExtractor + NSMutableData

Tim Kozak
  • 3,030
  • 31
  • 35
5

I don't personally know how to download youtube videos (and the code is too big to put in an answer here).

However, here's a complete youtube downloading example here. It's an open source youtube downloader called LoadTube: here's the a link to the source code.

Kyle Howells
  • 2,914
  • 1
  • 24
  • 35
5

check these projects -

https://github.com/iosdeveloper/MyTube
https://github.com/pvinis/mytube

these will definitely help you!!

Saurabh
  • 22,325
  • 12
  • 80
  • 133
1

I would play the video and figure out where the temp file is being stored. If you can get access to it, copy it into some document folder for offline viewing.

Sean
  • 11
  • 1
  • Sean, that is some suggestion. But implementation that I saw in some Chinese app shows custom progress download and allows to play at any time after download, no need to play it first. One can have many downloads progressing at the same time. – Biko Feb 23 '11 at 11:42
  • In my sandbox (https://github.com/comonitos/youtube_video). I download video from youtube in documents folder. For showing progress you can use NSURLConnection delegate or ASIHTTPRequest (allseeing-i.com/ASIHTTPRequest): 1- app getting youtube url. 2 ASIHTTPRequest || NSURLConnection - download with showing progress. – Tim Kozak Mar 09 '12 at 08:41