Swift 4 update (with removed force unwrapping):
func playInYoutube(youtubeId: String) {
if let youtubeURL = URL(string: "youtube://\(youtubeId)"),
UIApplication.shared.canOpenURL(youtubeURL) {
// redirect to app
UIApplication.shared.open(youtubeURL, options: [:], completionHandler: nil)
} else if let youtubeURL = URL(string: "https://www.youtube.com/watch?v=\(youtubeId)") {
// redirect through safari
UIApplication.shared.open(youtubeURL, options: [:], completionHandler: nil)
}
}
Don't forget to add youtube
scheme to LSApplicationQueriesSchemes
in Info.plist
(otherwise canOpenURL
will always fail):
<key>LSApplicationQueriesSchemes</key>
<array>
<string>youtube</string>
</array>
Sidenote:
If the user enabled Safari app to open Youtube app before, you don't need to go through youtube://
scheme and the second url will open Youtube app, too. However, you cannot control that, and if the user declined Safari to open Youtube, then you will have to try the scheme directly anyway - therefore I believe it is better to use the solution I stated above with both conditional branches.