title: How do I asynchronously download and cache videos for use in my app?
body: <p>I know that <code>SDWebImage</code> loads the image in a background thread so you're not blocking the UI/main thread when this downloading is going on. Furthermore, it will also disk-cache all the images you've downloaded and will NEVER re-download an image from the same <code>URL</code>. </p>
  
  <p><strong>So I wonder if there is something similar or the same for videos?</strong> </p>
  
  <p><strong>Something to note:</strong> I add Videos as Sublayer.</p>
  
  <pre><code>let videoURL = URL(string: postArray[indexPath.item].media[0].videoURLString!)//need to do error handlin here
  print(videoURL as Any, "&lt;-- video url in dispkay")
  
  let player = AVPlayer(url: videoURL! as URL)
  let playerLayer = AVPlayerLayer(player: player)
  playerLayer.frame = CGRect(x: -8, y: 0, width: 138, height: 217)//cell.frame
  
  
  cell.imageOrVideoView.layer.addSublayer(playerLayer)
  //Other code and play()
  </code></pre>
  
  <p><a href="https://github.com/VeinGuo/VGPlayer" rel="noreferrer">This was recommended</a> in the past but it seems like it does something different or at the very leased has too much extra functionality I dont need. </p>
  
  <p><strong>Update:</strong></p>
  
  <p>What I am testing:</p>
  
  <pre><code>  DispatchQueue.global(qos: .default).async(execute: {
  
              var downloadedData: Data? = nil
              if let url = URL(string: videoURL) {
                  do {
                      downloadedData = try Data(contentsOf: url)
                  } catch {
                      print(error, "downloaded Data failed")
                  }
              }
  
              if downloadedData != nil {
  
                  // STORE IN FILESYSTEM
                  var cachesDirectory = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true)[0]
                  var file = URL(fileURLWithPath: cachesDirectory).appendingPathComponent(videoURL).absoluteString
                  do {
                      try downloadedData?.write(to: URL(string: file)!)
                  } catch {
                      print(error, "error dowloading data and writing it")
                  }
  
                  // STORE IN MEMORY
                  if let downloadedData = downloadedData {
                      memoryCache?.setObject(downloadedData as AnyObject, forKey: videoURL as AnyObject)
                  }
              }
  
              // NOW YOU CAN CREATE AN AVASSET OR UIIMAGE FROM THE FILE OR DATA
          })
  </code></pre>
  
  <p>I do not understand however if I should do something right after the last line or if I should do it after the }) or if I need to add a Update UI there.</p>