title: download youtube video offline swift
body: <p>I'm trying to download a youtube video on the phone so the user can later play it offline. I hooked a button to where the user can download. The code of how I'm currently downloading the video is here below.</p>
  
  <pre><code>@objc func downloadSelectedVideo() {
          if let audioUrl = URL(string: "http://freetone.org/ring/stan/iPhone_5-Alarm.mp3") {
              // create your document folder url
              let documentsUrl = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
              // your destination file url
              let destination = documentsUrl.appendingPathComponent(audioUrl.lastPathComponent)
              print(destination)
              // check if it exists before downloading it
              if FileManager().fileExists(atPath: destination.path) {
                  print("The file already exists at path")
              } else {
                  //  if the file doesn't exist
                  //  just download the data from your url
                  URLSession.shared.downloadTask(with: audioUrl, completionHandler: { (location, response, error) in
                      // after downloading your data you need to save it to your destination url
                      guard
                          let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200,
                          let mimeType = response?.mimeType, mimeType.hasPrefix("audio"),
                          let location = location, error == nil
                          else { return }
                      do {
                          try FileManager.default.moveItem(at: location, to: destination)
                          print("file saved")
                      } catch {
                          print(error)
                      }
                  }).resume()
              }
          }
      }
  </code></pre>
  
  <p>as you can see I have hooked up the URL to a free music which is in mp3 and it works fine I can download the music and everything works just fine, however when I try to hook up a YouTube video then it never gets to the print statement file saved I tried this as the URL <code>if let audioUrl = URL(string: "https://www.youtube.com/watch?v=3WSgJCYIewM")</code></p>
  
  <p>but the print statement file saved never ran, but when I tried with the other I mentioned earlier it print file saved.</p>
  
  <p>What URL should use to download the youtube videos, and do I have to use an mp3 or mp4 source to download the videos. I'm trying not to use any third-party sites if you can come up with any solution it would be great and helpful. Thanks</p>