更新:
此篇文章介紹的方法利用UIWebView播放youtube影片,
彼得潘的另一篇文章,播放天生愛情狂"張智霖"的Youtube MV ,
利用LBYouTubeView播放影片,效果更好,
建議採用LBYouTubeView的做法。
從App裡播放YouTube影片其實很簡單,
接下來彼得潘將以好朋友沈老師生動有趣的英文教學影片為例子,
讓大家學習消失多年的左右互搏之術,左手學App,右手學英文。
2. 定義播放youtube影片的addYouTubeVideoWebView: method
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
- (void)addYouTubeVideoWebView:(NSString*)youtubeUrl | |
{ | |
NSMutableString *html = [[NSMutableString alloc] init]; | |
[html appendString:@"<html><body style='margin:0'><iframe src='"]; | |
[html appendString:youtubeUrl]; | |
[html appendString:@"' width='320' height='200' frameborder='0'></iframe></body></html>"]; | |
UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 200)]; | |
[self.view addSubview:webView]; | |
[webView loadHTMLString:html baseURL:nil]; | |
} |
為了播放youtube影片,我們需要UIWebView幫忙。UIWebView不只精通於網頁,同時也擅長youtube。利用html的iframe標籤,即可將youtube影片置於UIWebView上。
3. 傳入youtube影片的URL
呼叫剛剛定義的addYouTubeVideoWebView: method,傳入youtube影片的URL,即可播放影片。以沈老師的教學影片為例,其URL原本為http://www.youtube.com/watch?v=ESo7GBC_em8&feature=youtu.be,但我們想要在html的iframe裡播放,必須採用embed URL。
此URL必須以http://www.youtube.com/embed/開頭,然後再於後頭接上ESo7GBC_em8,變為http://www.youtube.com/embed/ESo7GBC_em8
執行App:


Youtube影片完美地播放,就連水平全螢幕播放也難不倒它。大家快點一起加入左手學App,右手學英文的幸福旅程吧!
請問如何按下done鍵就跳回前一個controller呢?
回覆刪除建議可以參考我的另一篇文章 "播放天生愛情狂"張智霖"的Youtube MV",
回覆刪除http://deeploveapple.blogspot.tw/2012/10/youtube-mv.html
此篇的方法利用LBYouTubeView來播放youtube影片,效果更好。
LBYouTubeView實際上是運用iOS SDK內建的MPMoviePlayerController來播放影片,
所以可以利用以上程式偵測done鍵被按
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(doneButtonPressed:) name:MPMoviePlayerDidExitFullscreenNotification object:nil];