I am building an app in which i will be having a UIButton
named Watch Video
on clicking the button the YouTube app/web should be opened with the respective youtube ID.
I saw code to embed YouTube videos in iOS but i did not find anything of this sort. Any ideas would be really helpful.
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.
This way you first check if the YouTube app is installed on a device, and then open the app or else go to Safari.
let youtubeId = "SxTYjptEzZs"
var youtubeUrl = NSURL(string:"youtube://\(youtubeId)")!
if UIApplication.sharedApplication().canOpenURL(youtubeUrl){
UIApplication.sharedApplication().openURL(youtubeUrl)
} else{
youtubeUrl = NSURL(string:"https://www.youtube.com/watch?v=\(youtubeId)")!
UIApplication.sharedApplication().openURL(youtubeUrl)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With