Save Youtube video to iPhone in the app

Biko picture Biko · Feb 23, 2011 · Viewed 23.8k times · Source

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)

Answer

Anomie picture Anomie · May 23, 2011

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.