首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >检测UIWebView完成在iPad上播放youtube视频

检测UIWebView完成在iPad上播放youtube视频
EN

Stack Overflow用户
提问于 2012-02-27 03:32:59
回答 4查看 18.2K关注 0票数 10

我正在使用UIWebView在iPad中播放YouTube视频。

如何检测YouTube视频何时播放完毕?我在状态栏中看到了play图标,我尝试使用MPMusicPlayerController通知来检测playbackStateDidChange,但是它没有工作。

有什么办法能发现这个事件吗?再说一次,我说的是iPad而不是iPhone。

提前谢谢。

更新:

如果您使用零解决方案来检测播放结束,并且还希望Youtube视频自动启动,则将UIWebView设置为:

代码语言:javascript
运行
复制
self.webView.mediaPlaybackRequiresUserAction = NO ;

我只想澄清一下YouTube框架API:

“重要:这是一个实验性的特性,这意味着它可能会意外地改变”(08/05/2012)

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2012-05-07 02:53:19

不,没有办法直接从UIWebView获得网页事件。但是我们可以通过使用Javascript来实现这一点。

  • 首先,您使用自定义HTML中的嵌入Javascript来检测视频结束播放事件。
  • 然后尝试使用JavaScript加载自定义方案请求,UIWebView可以捕获请求。

这些链接可能有助于:

  1. 从JavaScript调用iPhone UIWebView中的Objective C
  2. 目标C中的Javascript回调
  3. YouTube iFrame API

用一个例子更新:

在UIWebView的代表中,我指出:

代码语言:javascript
运行
复制
#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加载网页时

代码语言:javascript
运行
复制
[self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle       mainBundle] pathForResource:@"youtube" ofType:@"html" ]]]];

在youtube.html中,我指出:

代码语言:javascript
运行
复制
<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>

你可以看到我添加了

代码语言:javascript
运行
复制
if (event.data == YT.PlayerState.ENDED) {
      window.location = "callback:anything";
    };

对于YouTube的iFrame API演示程序,它捕获播放器的最终播放事件并尝试加载一个带有“回调”方案的请求,然后UIWebView代表就可以捕获它。

可以使用此方法使用JavaScript触发任何事件;

票数 15
EN

Stack Overflow用户

发布于 2013-04-24 03:30:24

请参阅:

类/Reference.html

有一个可用的通知iOS 4.0,您可以使用它来检测youtube视频的完成播放

代码语言:javascript
运行
复制
 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(youTubePlayed:) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
票数 11
EN

Stack Overflow用户

发布于 2013-02-05 07:44:55

下面是@zero作为一个成熟的类供您使用的奇妙答案:

代码语言:javascript
运行
复制
@interface YouTubeWebView () <UIWebViewDelegate>

@end


@implementation YouTubeWebView 

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self == nil) return nil;

    self.mediaPlaybackRequiresUserAction = NO;
    self.delegate = self;
    self.alpha = 0;

    return self;
}

- (void)loadVideo:(NSString *)videoId
{
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"youtube" ofType:@"html"];
    //    if (filePath == nil)

    NSError *error;
    NSString *string = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error];
    // TODO: error check

    string = [NSString stringWithFormat:string, videoId];

    NSData *htmlData = [string dataUsingEncoding:NSUTF8StringEncoding];
    //    if (htmlData == nil)

    NSString *documentsDirectoryPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    NSString *targetPath = [documentsDirectoryPath stringByAppendingPathComponent:@"youtube.html"];
    [htmlData writeToFile:targetPath atomically:YES];

    [self loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:targetPath]]];
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    if ([[[request URL] scheme] isEqualToString:@"callback"]) {
        [self removeFromSuperview];

        NSString *documentsDirectoryPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
        NSString *targetPath = [documentsDirectoryPath stringByAppendingPathComponent:@"youtube.html"];
        NSError *error;
        [[NSFileManager defaultManager] removeItemAtPath:targetPath error:&error];
//        TODO: error check
    }

    return YES;
}

只需使用这个版本的youtube.html,它有一个替换代码(%@)来代替视频id:

代码语言:javascript
运行
复制
<html>
<head><style>body{margin:0px 0px 0px 44px;}</style></head>
<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: '320',
      width: '480',
      videoId: '%@',
      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"; 
    };
  }
  function stopVideo() {
    player.stopVideo();
  }
</script>
</body>
</html>

要实现这一点,我必须克服的唯一主要障碍是将文件作为字符串加载以进行替换。不幸的是,它必须再次编写为一个文件,以便自动播放工作。如果这对于您的用例来说不是必需的,那么可以直接将HTML作为字符串加载到web视图中。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9459711

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档