Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Launch YouTube App in iOS device

Tags:

youtube

ios

swift

I have webview displaying youtube video:

class ViewController: UIViewController {

@IBOutlet var webView: UIWebView!

override func viewDidLoad() {
    super.viewDidLoad()

    let url = NSURL(string: "http://www.cast.html")
    let request = NSURLRequest(URL: url!)

    webView.loadRequest(request)
}

HTML link looks like this:

<div class="h_iframe">
<iframe webkit-playsinline height="480" width="2" src="https://www.youtube.com/embed/ru1_lI84Wkw?feature=player_detailpage&playsinline=1" frameborder="0" allowfullscreen></iframe></div>

That works perfectly, but i want also to let user to watch it on the youtube app. Is it possible to create link in webview that launch YouTube app (if installed on device) ?

Any help appreciated.

like image 335
Jay Avatar asked Nov 17 '14 06:11

Jay


Video Answer


2 Answers

Since Youtube isn't pre-installed on the phone, it's a good idea to safeguard this by testing the URL then falling back to using safari if they don't have youtube installed.

Add this key to your info.plist

<key>LSApplicationQueriesSchemes</key>
<array>
   <string>youtube</string>
</array>

Then this is the code that will fallback to safari if the Youtube app isn't installed.

    let youtubeId = "vklj235nlw"
    var url = URL(string:"youtube://\(youtubeId)")!
    if !UIApplication.shared.canOpenURL(url)  {
        url = URL(string:"http://www.youtube.com/watch?v=\(youtubeId)")!
    }
    UIApplication.shared.open(url, options: [:], completionHandler: nil)
like image 144
William T. Avatar answered Oct 05 '22 18:10

William T.


You can use this:

UIApplication.sharedApplication().openURL("youtube://XXXXXX")

where XXXXXX is the code of the video in youtube.

like image 31
Gabriel Avatar answered Oct 05 '22 19:10

Gabriel