创建一个普通的
html
文件,将其命名为
youtubeEmbedding.html
并将其添加到你的项目中,在
youtubeEmbedding.html
中只需将下面的代码添加到
.html
文件中。
<!DOCTYPE html>
<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);
firstScriptTag.requestFullScreen();
var ytplayer = null;
function onYouTubePlayerAPIReady()
{
ytplayer = new YT.Player(
'player',
{
videoId:'%@',
width:'%0.0f',
height:'%0.0f', %@
playerVars:
{
'controls': %d,
'playsinline' : 0,
'rel':0,
'showinfo':0
},
});
}
function onPlayerReady(event)
{
event.target.playVideo();
}
function stopVideo()
{
if (ytplayer)
{
ytplayer.stopVideo();
ytplayer.clearVideo();
}
return 'STOPPED';
}
function playVideo()
{
if (ytplayer)
{
ytplayer.playVideo();
}
return 'PLAY';
}
function pauseVideo()
{
if (ytplayer)
{
ytplayer.pauseVideo();
ytplayer.clearVideo();
}
return 'PAUSED';
}
function getPlayerState()
{
return ytplayer.getPlayerState();
}
function isPlaying()
{
return (myPlayerState == YT.PlayerState.PLAYING);
}
function isPaused()
{
return (myPlayerState == YT.PlayerState.PAUSED);
}
function onPlayerError(event)
{
alert("Error");
}
</script>
</body>
在使用Web视图的控制器中,只需按以下方式操作。
- (void)viewDidLoad
{
BOOL autoPlay = NO;
NSString *youTubeVideoHTML = [[NSString alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"youtubeEmbedding" ofType:@"html"] encoding:NSUTF8StringEncoding error:nil];
NSString *autoPlayString = autoPlay ? @"events: {'onReady' : onPlayerReady }," : @"";
NSURL *url = [NSURL URLWithString:@"https://www.youtube.com/watch?v=AYo72E7ZMHM"];
NSString *lastComponent = [url query];
NSString *videoId = [lastComponent stringByReplacingOccurrencesOfString:@"v=" withString:@""];
NSInteger controls = 1;
NSString *html = [NSString stringWithFormat:youTubeVideoHTML, videoId, CGRectGetWidth(_webView.frame), CGRectGetHeight(_webView.frame), autoPlayString, controls];
_webView.mediaPlaybackRequiresUserAction = NO;
_webView.delegate = self;
[_webView loadHTMLString:html baseURL:[[NSBundle mainBundle] resourceURL]];
}
- (IBAction)playAction:(id)sender
{
[_webView stringByEvaluatingJavaScriptFromString:@"ytplayer.playVideo()"];
}
如果您有任何问题,请评论,希望这能对您有所帮助.. :)