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

时间:2012-02-27 03:32:59

标签: objective-c ipad youtube uiwebview

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

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

有关如何检测此事件的任何想法?我再次谈论iPad而不是iPhone。

提前致谢。

更新:

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

self.webView.mediaPlaybackRequiresUserAction = NO ;

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

  

“重要:这是一个实验性功能,这意味着可能   意外改变“(08/05/2012)

4 个答案:

答案 0 :(得分:15)

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

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

这些链接可能有所帮助:

  1. Calling Objective-C from JavaScript in an iPhone UIWebView

  2. Javascript callback in Objective-C

  3. YouTube iFrame API

  4. 更新了一个例子:

    在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触发任何事件;

答案 1 :(得分:11)

请参阅:

https://developer.apple.com/library/ios/#documentation/AVFoundation/Reference/AVPlayerItem_Class/Reference/Reference.html

iOS 4.0提供了一个通知,您可以使用它来检测YouTube视频播放完毕

 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(youTubePlayed:) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];

答案 2 :(得分:3)

这是@ zero的绝佳答案,作为一个完整的课程供您使用:

@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:

<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 :(得分:0)

这是Swift 3的回答

   NotificationCenter.default.addObserver(
    self,
    selector: #selector(self.videoEnded),
    name: .AVPlayerItemDidPlayToEndTime,
    object: nil)


}

func videoEnded(){
    print("video ended")
}