2015-11-01 58 views
0

我曾尝试使用下面的代码添加了一个视频我的观点:如何在点击播放时添加回调或获取通知?

let url = NSBundle.mainBundle().URLForResource("etude", withExtension:"mp4") 
player = AVPlayer(URL: url!) 
let playerViewController = AVPlayerViewController() 
playerViewController.player = player 
playerViewController.view.frame = CGRect(x: xPos, y: yPos, width: videoWidth, height: videoHeight) 
self.view.addSubview(playerViewController.view) 
self.addChildViewController(playerViewController) 

我当用户点击播放器上的播放按钮其他一些事件来触发。当发生这种情况时是否有一种很好的方式来设置回调,或者添加观察者来检测它?

+0

NSBundle.mainBundle()有一个方法URLForResource(WithExtension :) –

回答

0

是的,您可以注册playerViewController.player.rate的Key-Value-Observing。

看起来像

self.player.addObserver(observer:self,keyPath:"rate",options:0,context:nil) 

然后实现

func observeValueForKeyPath(_ keyPath: String?, 
        ofObject object: AnyObject?, 
        change change: [String : AnyObject]?, 
        context context: UnsafeMutablePointer<Void>) 
{ 
    if(self.player.rate==1){ 
    print("playing") 
    }else if(self.player.rate == 0){ 
    print("stopped") 
    } 
} 
+0

感谢beyowulf。我认为我们正走在正确的轨道上。尽管将0传递给选项,但我仍然遇到了一个问题。从我可以看到它应该是有效的按照文档[链接](https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Protocols/NSKeyValueObserving_Protocol/#//apple_ref/c/ tdef/NSKeyValueObservingOptions),但我得到一个不能转换Int错误。 –

相关问题