Launch YouTube app on iOS device

I have a webview with 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) } 

The HTML link is as follows:

 <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> 

This works fine, but I want to also let the user watch it in the YouTube app. Is it possible to create a link in webview that launches the YouTube application (if it is installed on the device)?

Any help was appreciated.

+5
source share
4 answers

You can use this:

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

where XXXXXX is the YouTube video code.

+8
source

Since Youtube is not pre-installed on the phone, it is recommended to protect it by testing the URL, and then return to using safari if you do not 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 be returned to the safari if the Youtube application is not 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) 
+12
source

Update for Swift 3 and iOS 10+

OK, there are two simple steps for this:

First you need to change Info.plist to a Youtube list on LSApplicationQueriesSchemes . Just open Info.plist as source code and paste this:

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

After that, you can open any Youtube URL in the Youtube application by simply replacing https:// with youtube:// . Here is the complete code, you can associate this code with any button that you use as an action:

 @IBAction func YoutubeAction() { let YoutubeID = "Ktync4j_nmA" // Your Youtube ID here let appURL = NSURL(string: "youtube://www.youtube.com/watch?v=\(YoutubeID)")! let webURL = NSURL(string: "https://www.youtube.com/watch?v=\(YoutubeID)")! let application = UIApplication.shared if application.canOpenURL(appURL as URL) { application.open(appURL as URL) } else { // if Youtube app is not installed, open URL inside Safari application.open(webURL as URL) } } 
+2
source

Swift 3

UIApplication.shared.openURL(URL(string: "http://youtube.com")!)

If the YouTube app is not installed, it opens Safari (web page)

0
source

Source: https://habr.com/ru/post/1207000/


All Articles