use*_*951 10 youtube objective-c uiwebview ipad
我正在用UIWebView
iPad播放YouTube视频.
如何检测YouTube视频何时播放完毕?我在状态栏中看到播放图标,我尝试使用MPMusicPlayerController
通知进行检测playbackStateDidChange
,但它无法正常工作.
有关如何检测此事件的任何想法?再说一次,我说的是iPad而不是iPhone.
提前致谢.
更新:
如果您使用零解决方案来检测播放结束并且还希望Youtube视频开始自动设置UIWebView
为:
self.webView.mediaPlaybackRequiresUserAction = NO ;
Run Code Online (Sandbox Code Playgroud)
我只是想澄清一下YouTube框架API:
"重要:这是一个实验性功能,这意味着它可能会意外地改变"(08/05/2012)
ZeR*_*eR0 15
不,没有办法直接从中获取网页事件UIWebView
.但我们可以通过使用Javascript来实现这一目标.
这些链接有助于:
更新了一个例子:
在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;
Run Code Online (Sandbox Code Playgroud)
}
在以下情况下加载网页viewDidLoad
:
[self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"youtube" ofType:@"html" ]]]];
Run Code Online (Sandbox Code Playgroud)
并在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>
Run Code Online (Sandbox Code Playgroud)
你可以看到我添加
if (event.data == YT.PlayerState.ENDED) {
window.location = "callback:anything";
};
Run Code Online (Sandbox Code Playgroud)
到YouTube的iFrame API演示,它捕获播放器结束播放事件并尝试使用方案"回调"加载请求,然后UIWebView Delegate可以捕获它.
您可以使用此方法使用JavaScript触发任何事件;
chi*_*228 11
请参考:
有一个iOS 4.0通知,你可以使用它来检测youtube视频完成播放
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(youTubePlayed:) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
Run Code Online (Sandbox Code Playgroud)