Search code examples
iosiphoneswiftytplayerviewytplayer

How to Open YouTube app with YouTube id on a button click in iOS


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.


Solution

  • 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)
        }