使用AVPlayerViewController

时间:2016-07-14 20:06:12

标签: swift firebase avplayer firebase-storage

构建一个允许用户将媒体上传到Firebase存储的应用。上传似乎工作正常,但我无法播放视频。

我将一个文件保存到应用程序以测试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()
    }
}

1 个答案:

答案 0 :(得分:2)

请检查问题。我使用YouTube上的正确解决方案对其进行了更新:YouTube