Search code examples
iosswiftavplayeravplayeritem

How to access the Video files, which are present in iOS Files App using AVPlayer in iOS swift?


I am trying to access the access the video files which are present in the iOS Files App. Trying to play videos using AVPlayer

I am able to access the videos but after some time when I try to access the same video I am getting the error from the AVPlayer.

let filemgr = FileManager.default
let docsDirURL = try! filemgr.url(for: .documentDirectory, 
  in: .userDomainMask, appropriateFor: nil, create: true)

let lastComp = docsDirURL.lastPathComponent
let pathy = "\(docsDirURL)"

if let urls = lap.videoURLs {
  self.lap = lap
  for url in urls {
    let urlComps = "\(url)".components(separatedBy: "/")
    var urlpath = ""
    for (index, element) in urlComps.enumerated() {
      if index > 9{
        urlpath +=  element + "/"
      }
    }

    print(urlpath)
    var pathz = pathy.replacingOccurrences(of: lastComp, with: urlpath)
    pathz = String(pathz.dropLast(2))
    print(pathz)

    let finalURL = NSURL(string: pathz)
//  let playerItem = AVPlayerItem(url: url as URL)
    let playerItem = AVPlayerItem(url: finalURL! as URL)
    playerItem.addObserver(self, forKeyPath: "status", options: .new, 
      context: &itemStatusContext)
    self.playerItems.append(playerItem)

    if self.queuePlayer == nil {
      self.queuePlayer = AVPlayer(playerItem: playerItem)
    }
  }
}

I expect to play videos normally as before but I can only access it for some time like one minute and then after I received an error.

Optional(Error Domain=NSURLErrorDomain Code=-1100 "The requested URL was not found on this server." UserInfo={NSLocalizedDescription=The requested URL was not found on this server., NSUnderlyingError=0x283368f90 {Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}}) and URLS: [<AVPlayerItem: 0x283c1d4a0, asset = <AVURLAsset: 0x2878f41c0, URL = file:///var/mobile/Containers/Data/Application/0CE62F51-77E0-4630-A3C4-1CE615ACCD26/tmp/uk.co.racelogic.Circuit-Tools-for-iOS-Inbox/VBOX0005_0001.mp4>>, <AVPlayerItem: 0x283c1d850, asset = <AVURLAsset: 0x2878f5520, URL = file:///var/mobile/Containers/Data/Application/0CE62F51-77E0-4630-A3C4-1CE615ACCD26/tmp/uk.co.racelogic.Circuit-Tools-for-iOS-Inbox/VBOX0005_0002.mp4>>]


Solution

  • So as stated in error "No such file or directory" a file is absent. Regarding full path it stored inside temporary folder. Probably you imported these files via UIDocumentPickerViewController or similar component. You must copy provided file immediately (synchronously) in same code block where you get the URL to some local storage to avoid this situation.