2017-08-02 46 views
0

我需要連續播放存儲在臨時目錄內的視頻。加載臨時視頻並播放

func setVideo(url vid: String!) { 

    let directory = NSTemporaryDirectory() 

    let tempURL = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("tempMovie\(Date().timeIntervalSince1970)").appendingPathExtension("mp4") 

    let tempFile = NSURL.fileURL(withPathComponents: [directory]) 


    let file = vid.components(separatedBy: ".") 

    guard let path = Bundle.main.path(forResource: "\(tempURL)", ofType:file[2]) else { 
     debugPrint("\(file.joined(separator: ".")) not found with path: \(file[0] + "." + file[1])") 
     return 
    } 
    let player = AVPlayer(url: URL(fileURLWithPath: path)) 

    let playerLayer = AVPlayerLayer(player: player) 
    playerLayer.frame = self.view.bounds 
    self.videoView.layer.addSublayer(playerLayer) 
    player.play() 


    NotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object: self.player.currentItem, queue: nil, using: { (_) in 
     DispatchQueue.main.async { 
      self.player?.seek(to: kCMTimeZero) 
      self.player?.play() 
     } 
    }) 

} 

視頻的位置和文件的URL是:

file:///private/var/mobile/Containers/Data/Application/E7D12401-F147-4905-83BE-72909F91E004/tmp/tempMovie1501672791.33525.mp4 

連續環狀部分從以前的項目工程,但是我似乎無法獲得臨時存儲的視頻播放器內加載。我試圖手動獲取臨時目錄,但它不起作用。

回答

1

將視頻從tmp移動到Documents目錄爲我工作。

這是你如何做到這一點:

let documentsDirectoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first! 

    let destinationURL = documentsDirectoryURL.appendingPathComponent("filename.fileExtension") 

     do { 

      try FileManager.default.moveItem(at: previousTempLocation, to: destinationURL) 

     } catch let error as NSError { print(error.localizedDescription)} 

    let player = AVPlayer(url: destinationURL)  

蘋果公司說,這在/ tmp目錄

使用此目錄編寫不需要 臨時文件啓用您的應用之間仍然存在。不再需要時,您的應用程序應從此目錄中刪除文件 ;但是,當您的應用程序未運行時, 系統可能會清除此目錄。

蘋果還建議該用戶數據文件

放置用戶數據/。用戶數據通常包括您可能想要向用戶公開的任何文件 --您可能希望用戶 創建,導入,刪除或編輯的任何內容。視頻和音頻應用程序甚至可能包含用戶已下載以供稍後觀看或收聽的 文件。