【问题标题】:Objective-C: Play Youtube Video on AppObjective-C:在 App 上播放 Youtube 视频
【发布时间】:2013-03-07 14:54:55
【问题描述】:

我正在尝试探索在 iOS 应用程序开发中我还能做些什么,而我刚刚尝试在我的应用程序中包含一个视频。

我在下面有这段代码,旨在在视图加载时播放 youtube 视频,但我得到的只是一个黑色的 webView。

NSString *videoURL = @"http://youtu.be/Wq_CtkKrt1o";

videoView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 768, 1024)];
videoView.backgroundColor = [UIColor clearColor];
videoView.opaque = NO;
videoView.delegate = self;
[self.view addSubview:videoView];


NSString *videoHTML = [NSString stringWithFormat:@"\
             <html>\
             <head>\
             <style type=\"text/css\">\
             iframe {position:absolute; top:50%%; margin-top:-130px;}\
             body {background-color:#000; margin:0;}\
             </style>\
             </head>\
             <body>\
             <iframe width=\"100%%\" height=\"240px\" src=\"%@\" frameborder=\"0\" allowfullscreen></iframe>\
             </body>\
             </html>", videoURL];

[videoView loadHTMLString:videoHTML baseURL:nil];

【问题讨论】:

  • 你是在模拟器还是设备上试试这个?
  • @MikeD 我正在设备上测试它。

标签: ios objective-c uiwebview youtube-api


【解决方案1】:

你能试试下面的代码吗,它对我来说很好用

- (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];
}

【讨论】:

  • 还是不行。我是否需要包含任何框架来实现这一点??
  • 你能看看这个链接吗?你的 youtube 网址似乎是问题所在。 developer.apple.com/library/ios/#featuredarticles/…
  • 代码正常,但视频无法播放,尽快给出解决方案
  • 在模拟器中尝试?您正在使用什么 youtube 网址。
【解决方案2】:

你必须使用嵌入链接

使用下面的代码

NSString *videoURL = @"http://www.youtube.com/embed/Wq_CtkKrt1o";

而不是

NSString *videoURL = @"http://youtu.be/Wq_CtkKrt1o";

试试这个你的问题会解决的

【讨论】:

  • 谢谢!它现在正在工作。但是,我已经在我的 iPad 4th Gen 上试过了,它没有声音,在 Mini 上声音很好。这是为什么?我检查了所有声音设置,一切都很好。
  • iOS版本分别是什么?
  • 太棒了!感谢负载
猜你喜欢
  • 2013-07-12
  • 2013-02-09
  • 2011-06-26
  • 2013-11-19
  • 2014-05-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-23
  • 1970-01-01
相关资源
最近更新 更多