Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 568
Manju Basha Avatar asked Jan 09 '17 06:01

Manju Basha


2 Answers

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.

like image 69
Milan Nosáľ Avatar answered Sep 24 '22 05:09

Milan Nosáľ


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)
    }
like image 21
Arpit Dongre Avatar answered Sep 24 '22 05:09

Arpit Dongre