2
構建允許用戶將媒體上傳到Firebase存儲的應用。上傳似乎工作正常,但我無法播放視頻下載。保存Firebase存儲視頻並使用AVPlayerViewController播放
我保存了一個文件到應用程序來測試AVPlayer,它的工作原理非常完美。
func handleGesture() {
print("handle gesture")
if detailMediaType == "Video"{
performSegueWithIdentifier("toVideoView", sender: self)
print("video segue called")
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if(segue.identifier == "toVideoView"){
let path = NSBundle.mainBundle().pathForResource("Apartment Ceiling Collapse- Queens, NY", ofType: "mp4")
var movieUrl = NSURL(fileURLWithPath: path!)
let filename = getDocumentsDirectory().stringByAppendingPathComponent("movie")
let videoData = NSData(contentsOfURL: movieUrl)
videoData!.writeToFile(filename, atomically: true)
self.avPlayer = AVPlayer(URL: movieUrl)
self.avPlayerViewController.player = self.avPlayer
self.presentViewController(self.avPlayerViewController, animated: false) {() -> Void in self.avPlayerViewController.player?.play()
}
}
}
編輯:我現在嘗試使用downloadURLWithCompletion
FIRStorage.storage().referenceForURL(detailFullsizeUrl).downloadURLWithCompletion { (URL, error) -> Void in
if (error != nil)
{
print(error!)
}
else
{
self.firebaseUrl = URL!
print("firebaseUrl")
print(self.firebaseUrl)
self.avPlayer = AVPlayer(URL: self.firebaseUrl)
self.avPlayerViewController.player = self.avPlayer
}
}
我得到一個AVPlayerViewController黑屏下載。當我從網上訪問「firebaseUrl」時,它會下載一個看起來像亂碼的文本文件。
解決方案: 改變了我的方法。不再保存到設備。相反,我從Firebase存儲對象中抓取了「downloadUrl」元數據,並將其直接傳遞給AVPlayerViewController。
let avPlayerViewController = AVPlayerViewController()
var avPlayer:AVPlayer? = nil
override func viewDidLoad() {
super.viewDidLoad()
FIRStorage.storage().referenceForURL(detailFullsizeUrl).metadataWithCompletion { (metadata, error) in
if error != nil{
print("error getting metadata")
} else {
let downloadUrl = metadata?.downloadURL()
print(downloadUrl)
if downloadUrl != nil{
self.avPlayer = AVPlayer(URL: downloadUrl!)
self.avPlayerViewController.player = self.avPlayer
print("downloadUrl obtained and set")
}
}
}
}
func handleGesture() {
print("handle gesture")
self.presentViewController(self.avPlayerViewController, animated: true) {() -> Void in
self.avPlayerViewController.player?.play()
}
}