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

前端 未结 8 2186
南旧
南旧 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条回答
  •  -上瘾入骨i
    2020-12-13 16:29

    Apple changed how YouTube videos are handled in iOS6. I also was using the findButtonInView method but that no longer works.

    I've discovered the following seems to work (untested in iOS < 6):

    - (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\");\
                if (vph5) {\
                    vph5.playVideo();\
                } else {\
                    setTimeout(pollToPlay, 100);\
                }\
            }\
            pollToPlay();\
         "];
    }
    

提交回复
热议问题