YouTube video playback broken on iOS6 (works fine on iOS5)

前端 未结 8 2187
南旧
南旧 2020-12-13 16:13

In my app, I have a button which, when pressed, lets you watch a youtube video (a movie trailer). Within the app, without launching safari. Below you can see a code snippet.

8条回答
  •  攒了一身酷
    2020-12-13 16:34

    dharmabruce solution works great on iOS 6, but in order to make it work on iOS 5.1, I had to substitute the javascript click() with playVideo(), and I had to set UIWebView's mediaPlaybackRequiresUserAction to NO

    Here's the modified code:

    - (void)viewDidLoad 
    {
        [super viewDidLoad];
        self.webView.mediaPlaybackRequiresUserAction = NO;
    }
    
    - (void)playVideo
    {
        self.autoPlay = YES;
        // Replace @"y8Kyi0WNg40" with your YouTube video id
        [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@", @"http://www.youtube.com/embed/", @"y8Kyi0WNg40"]]]];
    }
    
    // UIWebView delegate
    - (void)webViewDidFinishLoad:(UIWebView *)webView {
        if (self.autoPlay) {
            self.autoPlay = NO;
            [self clickVideo];
        }
    }
    
    - (void)clickVideo {
        [self.webView stringByEvaluatingJavaScriptFromString:@"\
            function pollToPlay() {\
                var vph5 = document.getElementById(\"video-player-html5\");\
                if (vph5) {\
                    vph5.playVideo();\
                } else {\
                    setTimeout(pollToPlay, 100);\
                }\
            }\
            pollToPlay();\
         "];
    }
    

提交回复
热议问题