Update for Swift 3 and iOS 10+
OK, there are two easy steps to achieve this:
First, you have to modify Info.plist
to list Youtube
with LSApplicationQueriesSchemes
. Simply open Info.plist
as a Source Code, and paste this:
<key>LSApplicationQueriesSchemes</key>
<array>
<string>youtube</string>
</array>
After that, you can open any youtube URL inside Youtube application by simply substituting https://
with youtube://
. Here is a complete code, you can link this code to any button you have as an Action:
@IBAction func YoutubeAction() {
let YoutubeQuery = "Your Query"
let escapedYoutubeQuery = YoutubeQuery.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
let appURL = NSURL(string: "youtube://www.youtube.com/results?search_query=\(escapedYoutubeQuery!)")!
let webURL = NSURL(string: "https://www.youtube.com/results?search_query=\(escapedYoutubeQuery!)")!
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)
}
}