我的YoutubePlayer中没有显示视频

时间:2014-11-12 10:50:39

标签: ios uiwebview youtube-api nsurl

我在我的WebView上显示视频,视频ID越来越完美,但视频没有显示在我的WebView上。这是我的代码

- (NSString *)htmlContent
 {

NSURL*link=[NSURL URLWithString:@"http://www.youtube.com/watch?v=LIuk1qu0RlU&feature=youtube_gdata_player"];
videoId = [[NSString alloc]init];
NSArray *queryComponents = [link.query componentsSeparatedByString:@"&"];
for (NSString* pair in queryComponents)
{
    NSArray* pairComponents = [pair componentsSeparatedByString:@"="];
    if ([pairComponents[0] isEqualToString:@"v"])
    {
        videoId = pairComponents[1];
        NSLog(@"Embed video id: %@", videoId);
        break;
    }
}

if (!videoId)
{
    [[[UIAlertView alloc] initWithTitle:@"Error" message:@"Video ID not found in video URL" delegate:nil cancelButtonTitle:@"Close" otherButtonTitles: nil]show];

}

embedHTML = @"<!DOCTYPE html>\ <html>\ <head>\<style type='text/css' media='screen'>\body, p{\background-color: black;\margin: 0px;\}\#player {\width: 100%%;\}\</style>\</head>\<body><div id='player'></div>\<script type='text/javascript'>\var tag = document.createElement('script');\tag.src = 'https://www.youtube.com/iframe_api';\var firstScriptTag = document.getElementsByTagName('script')[0];\firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);\ \ var player;\function onYouTubeIframeAPIReady() {\player = new YT.Player('player', {\height: '%f',\ width: '%f',\videoId: '%@',\events: {\'onReady': onPlayerReady,\}\});\}\\function onPlayerReady(event) {\event.target.playVideo();\}\\</script>\</body>\</html>";
CGSize playerSize = [self playerSize];
NSString *result = [NSString stringWithFormat:embedHTML,playerSize.width,playerSize.height,videoId];
return result;
 }


-(void)viewWillAppear:(BOOL)animated
{
       [self.playerwebview loadHTMLString:[self htmlContent] 
       baseURL:[NSURL URLWithString:@"http://www.youtube.com"]];
}

任何人都可以告诉我这里我做错了什么。 感谢

1 个答案:

答案 0 :(得分:0)

CGRect screenRect = [[UIScreen mainScreen] bounds];

CGFloat screenWidth = screenRect.size.width;

CGFloat screenHieght = screenRect.size.height;

int width = (int) roundf(screenWidth);

int height = (int) roundf(screenHieght);

NSString *youTubeVideoHTML = @"<html><head><style>body{margin:0px 0px 0px 0px; }</style></head> <body> <div id=\"player\"></div> <script> var tag = document.createElement('script'); tag.src = 'http://www.youtube.com/player_api'; var firstScriptTag = document.getElementsByTagName('script')[0]; firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); var player; function onYouTubePlayerAPIReady() { player = new YT.Player('player', { width:'%d', height:'%d', videoId:'%@', events: { 'onReady': onPlayerReady } }); } function onPlayerReady(event) { event.target.playVideo(); } </script> </body> </html>";

NSString *html = [NSString stringWithFormat:youTubeVideoHTML,width,height,YouTubeId];

[_webView loadHTMLString:html baseURL:[[NSBundle mainBundle] resourceURL]];

用上面的代码块替换你的代码,我希望它适用于你的