我创建了一个简单的ViewController
课程,使用AVPlayer
播放直播视频。直播加载在viewDidLoad
中,当用户按下播放时,它会播放实时流,非常简单。
父VC仅设置为纵向。
我有另一个按钮,使用自定义segue转换为另一个ViewController
。
如何通过AVPlayer及其状态"到目的地ViewController
?......即。如果AVPlayer当前正在播放,它应该在从父VC传递到目标VC时保持其状态。
仅供参考:我没有使用prepareForSegue
。
这是完整的简单代码:
ViewController.swift:
class ViewController: UIViewController {
@IBOutlet var playerView: UIView!
var player = AVPlayer()
var avPlayerLayer: AVPlayerLayer!
override func viewDidLoad()
{
super.viewDidLoad()
let url = "http://vevoplaylist-live.hls.adaptive.level3.net/vevo/ch1/appleman.m3u8" //"http://68.235.37.11:1935/vietmagazine/vietmagazine/playlist.m3u8"
let playerItem = AVPlayerItem( URL:NSURL( string:url )! )
player = AVPlayer(playerItem:playerItem)
avPlayerLayer = AVPlayerLayer(player: player)
// Add the layer to the view
playerView.layer.insertSublayer(avPlayerLayer, atIndex: 0)
}
@IBAction func playVIdeo(sender: AnyObject)
{
avPlayerLayer.player!.play()
}
@IBAction func change(sender: AnyObject)
{
avPlayerLayer.player!.pause()
self.performSegueWithIdentifier("CustomSegue", sender: self)
}
override func viewWillLayoutSubviews()
{
super.viewWillLayoutSubviews()
// Layout subviews manually
avPlayerLayer.frame = playerView.bounds
}
}
CustomSegue.swift:
class CustomSegue: UIStoryboardSegue
{
override func perform()
{
let sourceVC = self.sourceViewController
let destinationVC = self.destinationViewController
sourceVC.view.addSubview(destinationVC.view)
destinationVC.view.transform = CGAffineTransformMakeScale(0.05, 0.05)
UIView.animateWithDuration(0.5, delay: 0.0, options: .CurveEaseInOut, animations: { () -> Void in
destinationVC.view.transform = CGAffineTransformMakeScale(1.0, 1.0)
} ) { (finished) -> Void in
destinationVC.view.removeFromSuperview()
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(0.001 * Double(NSEC_PER_SEC)))
dispatch_after(time, dispatch_get_main_queue(), { () -> Void in
sourceVC.presentViewController(destinationVC, animated: false, completion: nil)
})
}
}
}
感谢。
答案 0 :(得分:0)
传递AVPlayer
实例是否足以传递玩家及其状态?
未经测试,但这有效吗?在第一个视图控制器中:
class ViewController: UIViewController {
var player = AVPlayer()
@IBAction func myAction(sender: AnyObject) {
performSegueWithIdentifier("TheSegue", sender: self)
}
}
class MySegue: UIStoryboardSegue {
override func perform() {
let viewController = sourceViewController as! ViewController
let secondViewController = destinationViewController as! SecondViewController
secondViewController.player = viewController.player
sourceViewController.presentViewController(destinationViewController, animated: true, completion: nil)
}
}
在第二个视图控制器中:
class SecondViewController: UIViewController {
var player: AVPlayer!
override func viewDidLoad() {
// Do something with the player
}
}
注意,this answer显示了如何检查AVPlayer
;的状态。