ios 将 YouTube 视频嵌入到

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5117617/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 19:01:30  来源:igfitidea点击:

Embedding YouTube videos on

iphoneobjective-ciosyoutube

提问by ayve

I've embedded a video from YouTube via a snippet I've found on the Internet, here is the code that I've used:

我通过在互联网上找到的片段嵌入了来自 YouTube 的视频,这是我使用的代码:

    @interface FirstViewController (Private)
- (void)embedYouTube:(NSString *)urlString frame:(CGRect)frame;
@end


@implementation FirstViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self embedYouTube:@"http://www.youtube.com/watch?v=l3Iwh5hqbyE" frame:CGRectMake(20, 20, 100, 100)];
}


- (void)embedYouTube:(NSString *)urlString frame:(CGRect)frame {
    NSString *embedHTML = @"\
    <html><head>\
    <style type=\"text/css\">\
    body {\
    background-color: transparent;\
    color: white;\
    }\
    </style>\
    </head><body style=\"margin:0\">\
    <embed id=\"yt\" src=\"%@\" type=\"application/x-shockwave-flash\" \
    width=\"%0.0f\" height=\"%0.0f\"></embed>\
    </body></html>";
    NSString *html = [NSString stringWithFormat:embedHTML, urlString, frame.size.width, frame.size.height];
    UIWebView *videoView = [[UIWebView alloc] initWithFrame:frame];
    [videoView loadHTMLString:html baseURL:nil];
    [self.view addSubview:videoView];
    [videoView release];
}


- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
}

@end

It compiles correctly and when I open it, I see a white box positioned incorrectly, which the code created. I have two questions regarding it:

它编译正确,当我打开它时,我看到一个白框位置不正确,这是代码创建的。我有两个问题:

  1. How do I know if the video will play, it is just a plain white box, does the simulator play videos from YouTube?

  2. How can I position this box?

  1. 我怎么知道视频是否会播放,它只是一个普通的白色框,模拟器是否播放来自 YouTube 的视频?

  2. 我如何定位这个盒子?

采纳答案by Julio Gorgé

Just tested your code, it works fine on an iPhone, Youtube videos are not supported on the iOS simulator though, so you'll need a real device for testing.

刚刚测试了您的代码,它在 iPhone 上运行良好,但 iOS 模拟器不支持 Youtube 视频,因此您需要一个真实的设备进行测试。

How can I position this box?

我如何定位这个盒子?

You are already passing the X (20), Y(20), width(100) and height(100) of the box at this line:

您已经在这一行传递了盒子的 X (20)、Y(20)、宽度(100) 和高度(100):

[self embedYouTube:@"http://..." frame:CGRectMake(20, 20, 100, 100)];

To change the position of the view afterwards, you modify its center property:

之后要更改视图的位置,请修改其 center 属性:

videoView.center = CGPointMake(200, 100 );

回答by Nikesh K

Here is the sample code, its working fine on iOS 5 and later, this is the new implementation which Youtube API provided, myWebis a UIWebView here. showinfo=0in URL will remove the top header in the videoView.

这是示例代码,它在 iOS 5 及更高版本上运行良好,这是 Youtube API 提供的新实现,myWeb这里是一个 UIWebView。 showinfo=0在 URL 中将删除 videoView 中的顶部标题。

NSString *html = [NSString stringWithFormat:@"<html><body><iframe class=\"youtube-player\" type=\"text/html\" width=\"%f\" height=\"%f\" src=\"http://www.youtube.com/embed/q1091sWVCMI?HD=1;rel=0;showinfo=0\" allowfullscreen frameborder=\"0\" rel=nofollow></iframe></body></html>",frame.size.width,frame.size.height];
[myWeb loadHTMLString:html baseURL:nil];

Hope this helps you :)

希望这对你有帮助:)

回答by adriandz

Here's a version that works in iOS 6 and with the new YouTube embed code:

这是一个适用于 iOS 6 和新的 YouTube 嵌入代码的版本:

- (void)embedYouTube:(NSString *)urlString frame:(CGRect)frame {
    NSString *html = [NSString stringWithFormat:@"<html><head><style type='text/css'>body {background-color: transparent;color: white;}</style></head><body style='margin:0'><iframe width='%f' height='%f' src='%@' frameborder='0' allowfullscreen></iframe></body></html>", frame.size.width, frame.size.height, urlString];
    UIWebView *videoView = [[UIWebView alloc] initWithFrame:frame];
    [videoView loadHTMLString:html baseURL:nil];
    [self.view addSubview:videoView];
}

回答by JAL

Swift Implementation:

快速实施:

let webView = UIWebView(frame: self.view.frame) // Position your player frame here

self.view.addSubview(webView)
self.view.bringSubviewToFront(webView)

// Playback options: play in-line and start playing immediately
webView.allowsInlineMediaPlayback = true
webView.mediaPlaybackRequiresUserAction = false

// Set the id of the video you want to play
let videoID = "zN-GGeNPQEg" // https://www.youtube.com/watch?v=zN-GGeNPQEg

// Set up your player
let embededHTML = "<html><body style='margin:0px;padding:0px;'><script type='text/javascript' src='http://www.youtube.com/iframe_api'></script><script type='text/javascript'>function onYouTubeIframeAPIReady(){ytplayer=new YT.Player('playerId',{events:{onReady:onPlayerReady}})}function onPlayerReady(a){a.target.playVideo();}</script><iframe id='playerId' type='text/html' width='\(self.view.frame.size.width)' height='\(self.view.frame.size.height)' src='http://www.youtube.com/embed/\(videoID)?enablejsapi=1&rel=0&playsinline=1&autoplay=1' frameborder='0'></body></html>"

// Load the HTML into your UIWebView
webView.loadHTMLString(embededHTML, baseURL: NSBundle.mainBundle().bundleURL)

Alternatively, YouTube provides a great helper classfor devs to set up YouTube playback in their iOS which sets up the UIWebViewfor you.

或者,YouTube为开发人员提供了一个很好的帮助类,可以在他们的 iOS 中设置 YouTube 播放,UIWebView为您设置。

回答by Quiet Islet

swift 4

迅捷 4

func embedYouTube(_ urlString: String, frame: CGRect) {

func embedYouTube(_ urlString: String, frame: CGRect) {

    let html = "<html><head><style type='text/css'>body {background-color: transparent;color: white;}</style></head><body style='margin:0'><iframe width='\(frame.size.width)' height='\(frame.size.height)' src='\(urlString)' frameborder='0' allowfullscreen></iframe></body></html>"
    let videoView = UIWebView(frame: frame)
    videoView.loadHTMLString(html, baseURL: nil)
    view.addSubview(videoView)
}

回答by TChadwick

For those using Monotouch and C#, you can add this class to your project and use it to view your videos:

对于使用MonoTouch的和C#的,你可以将该类添加到您的项目,并用它来查看您的视频:

public class YouTubeViewer : UIWebView
{
    public YouTubeViewer(string url, RectangleF frame)
    {
        string youTubeVideoHTML = @"<object width=""{1}"" height=""{2}""><param name=""movie""
                            value=""{0}""></param><embed
                            src=""{0}"" type=""application/x-shockwave-flash"" 
                            width=""{1}"" height=""{2}""</embed></object>"; 

        string html = string.Format(youTubeVideoHTML, url, frame.Size.Width, frame.Size.Height);
        this.LoadHtmlString(html, null);
        this.Frame = frame;
    }
}

Make sure the URL you pass it, is the URL from the embed code provided from Youtube when you click the Share button. (And check the check-box for the old code)

确保您传递的 URL 是来自 Youtube 提供的嵌入代码的 URL,当您单击“共享”按钮时。(并选中旧代码的复选框)