2017-08-04 37 views
-3

我正在從聊天服務器下載NSData文件,並且我知道這個文件通常是作爲視頻文件上傳的。我想獲得這個文件並將其顯示爲視頻Safari。我認爲爲了做到這一點,我無法將其顯示爲NSData,是嗎?如果沒有,我可以讓這個文件在我的iPhone中顯示的格式是什麼?如何將下載的NSData類型轉換爲在iPhone Swift上播放的視頻類型?

所以我開始考慮再次將其轉換回一個視頻文件,這裏是我使用了基於this answer: How to convert video data to NSURL

答案如何解釋,我們可以將視頻轉換爲URL用它來打視頻稍後。我已經嘗試瞭解決方案並獲得了URL。然而,我得到的string類型的url無法在Safari上播放,所以我認爲我可能會做錯某些事情。我認爲這個錯誤可能來自於我使用編碼的方式,因爲我不知道該如何放置它。

請注意,filePath是包含NSData文件路徑的文件。

  let filePath = self.documentsPathForFileName(name: "video.mov") 


      do { try [videomessage?.url.write(toFile: filePath, atomically: true, encoding: String.Encoding.utf8)]} 
      catch{ 
       print ("error") 
      } 
      let videoFileURL = NSURL(fileURLWithPath: filePath) 

      print (videoFileURL) 

func documentsPathForFileName(name: String) -> String { 

    let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] 
    return documentsPath + name 
} 

回答

0

如果你實際上有Data的形式的視頻。所以,它需要先保存並轉換。試試這個:

[/*name of NSData*/ writeToFile:/*save file path*/ atomically: YES]; 
NSURL *filepath = [NSURL fileURLWithPath:/*save file path*/]; 
AVPlayerItem *player = [AVPlayerItem playerItemWithURL:filepath]; 

未經測試,但應該工作。

如果你已經有了URL那麼你就可以直接播放視頻:

func playVideo() { 

     // setup video player 
     let player = AVPlayer(url: videoUrl) 
     let playerViewController = AVPlayerViewController() 
     playerViewController.player = player 

     self.present(playerViewController, animated: true) { 
      playerViewController.player!.play() 
     } 

     // setup autorotate to landscape orientation 
     let value = UIInterfaceOrientation.landscapeRight.rawValue 
     UIDevice.current.setValue(value, forKey: "orientation") 
    } 
相關問題