在iPhone应用程序中播放YouTube视频而不使用UIWebView?

31

我希望在我的iPhone应用中播放YouTube视频。我已经尝试使用以下代码在我的iPhone应用中播放YouTube视频,

[self playVideo:@"http://www.youtube.com/watch?v=WL2l_Q1AR_Q" frame:CGRectMake(20, 70, 280, 250)];

- (void)playVideo:(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];
    NSLog(@"%@",html);
}

但是,这段代码对我不起作用。我也尝试过使用 MPMoviePlayerController 的代码,它是这样的:

NSURL *fileURL = [NSURL URLWithString:@"http://www.youtube.com/watch?v=WL2l_Q1AR_Q"];
MPMoviePlayerController *moviePlayerController = [[MPMoviePlayerController alloc] initWithContentURL:fileURL]; 
[moviePlayerController.view setFrame:CGRectMake(0, 70, 320, 270)]; 
[self.view addSubview:moviePlayerController.view];  
moviePlayerController.fullscreen = YES;  
[moviePlayerController play];

这对我也没有用。请问有人能告诉我我的问题出在哪里,并给我一些建议吗?我想在MPMoviewPlayerController中播放YouTube视频,而不是使用UIWebView。提前感谢。


相关链接:https://dev59.com/AnI-5IYBdhLWcg3wlpeW - Bill the Lizard
5个回答

10

只需要使用XCDYouTubeVideoPlayerViewController,它可以将YouTube视频无缝地添加到您的应用程序中,而无需使用UIWebView

它使用渐进式下载+MoviePlayerAVFoundation框架。只需提供YouTube视频ID即可开始使用。

它支持全屏和非全屏播放,并且在iOS模拟器上工作!

示例:

XCDYouTubeVideoPlayerViewController *videoPlayerViewController = [[XCDYouTubeVideoPlayerViewController alloc] initWithVideoIdentifier:@"9bZkp7q19f0"];
[self presentMoviePlayerViewControllerAnimated:videoPlayerViewController];

我使用Pod添加了这个库,我需要使用哪个头文件? - R. Mohan
@R.Mohan 应该是 #import <XCDYouTubeKit/XCDYouTubeKit.h> - Hlung

8

该库仅使用 UIWebView - Zeeshan

7

Yuvaraj先生,您的代码是正确的。请在您的iPhone/iPod touch设备上运行该项目,因为YouTube视频可能不支持/无法在模拟器上工作。请注意这一点。谢谢。


Gopinath先生,感谢您的回答。我会检查您的答案。谢谢。 - Yuvaraj.M

1

在Swift 4.1中播放YouTube视频

添加Pod pod 'XCDYouTubeKit'

在ViewController中导入XCDYouTubeKit

func playYoutubeVideo(){

let strUrl = "https://www.youtube.com/watch?v=9m_K2Yg7wGQ"
if let range = strUrl.range(of: "=") {
        let strIdentifier = strUrl.substring(from: range.upperBound)
        print("Identifier:\(strIdentifier)")
        let videoPlayerViewController = 
        XCDYouTubeVideoPlayerViewController(videoIdentifier: strIdentifier)
        videoPlayerViewController.present(in: viewYTVideo)
        videoPlayerViewController.moviePlayer.play()
    }
}

1

不要使用你目前正在使用的HTML嵌入代码,而是前往YouTube网站,找到一个视频,使用分享按钮,然后使用嵌入按钮获取一些示例嵌入HTML。使用该模式来嵌入视频,而不是你目前正在使用的Flash版本。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接