我正在使用UIWebView在iPad上播放YouTube视频.
YouTube视频播放完毕后如何检测?
我在状态栏中看到播放图标,我试图使用MPMusicPlayerController通知来检测playStateDidChange,但没有帮助.
任何想法如何检测这个事件?再次我在说iPad不是iPhone.
提前致谢.
更新:如果您使用零解决方案来检测播放的结束,并且还希望YouTube开始自动将UIWebView设置为:
self.webView.mediaplaybackRequiresUserAction = NO;
只是想澄清一下YouTube框架api:“重要提示:这是一个实验功能,这意味着它可能会意外地改变”(08/05/2012)
解决方法
不,没有办法直接从UIWebView获取网页事件.但是我们可以通过使用
Javascript来实现这一点.
>首先,在自定义HTML中使用嵌入JavaScript,以检测视频结束播放事件.
>然后,您尝试使用JavaScript加载方案自定义请求,UIWebView可以捕获请求.
这些链接可能有助于:
> Calling Objective-C from JavaScript in an iPhone UIWebView
> Javascript callback in Objective-C
> YouTube iFrame API
以示例更新:
在UIWebView的代表中,我把:
#pragma - mark WebView Delegate
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
if ( [[[request URL] scheme] isEqualToString:@"callback"] ) {
NSLog(@"get callback");
return NO;
}
return YES;
}
当viewDidLoad时,网页加载:
[self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"youtube" ofType:@"html" ]]]];
在youtube.html我放:
<html>
<body>
<!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
<div id="player"></div>
<script>
// 2. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "http://www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag,firstScriptTag);
// 3. This function creates an <iframe> (and YouTube player)
// after the API code downloads.
var player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('player',{
height: '390',width: '640',videoId: 'u1zgFlCw8Aw',events: {
'onReady': onPlayerReady,'onStateChange': onPlayerStateChange
}
});
}
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
event.target.playVideo();
}
// 5. The API calls this function when the player's state changes.
// The function indicates that when playing a video (state=1),// the player should play for six seconds and then stop.
var done = false;
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING && !done) {
setTimeout(stopVideo,6000);
done = true;
}
if (event.data == YT.PlayerState.ENDED) {
window.location = "callback:anything"; //here's the key
};
}
function stopVideo() {
player.stopVideo();
}
</script>
</body>
</html>
你可以看到我添加
if (event.data == YT.PlayerState.ENDED) {
window.location = "callback:anything";
};
到YouTube的iFrame API演示,它捕获播放器结束播放事件,并尝试使用方案“回调”加载请求,然后UIWebView Delegate可以捕获它.
您可以使用此方法来触发任何使用JavaScript的事件;