在iOS设备中启动YouTube App

Jay*_*Jay 9 youtube ios swift

我有webview显示youtube视频:

class ViewController: UIViewController {

@IBOutlet var webView: UIWebView!

override func viewDidLoad() {
    super.viewDidLoad()

    let url = NSURL(string: "http://www.cast.html")
    let request = NSURLRequest(URL: url!)

    webView.loadRequest(request)
}
Run Code Online (Sandbox Code Playgroud)

HTML链接如下所示:

<div class="h_iframe">
<iframe webkit-playsinline height="480" width="2" src="https://www.youtube.com/embed/ru1_lI84Wkw?feature=player_detailpage&playsinline=1" frameborder="0" allowfullscreen></iframe></div>
Run Code Online (Sandbox Code Playgroud)

这很完美,但我也想让用户在youtube应用程序上观看它.是否可以在webview中创建启动YouTube应用程序的链接(如果安装在设备上)?

任何帮助赞赏.

Wil*_* T. 20

由于Youtube没有预先安装在手机上,因此最好通过测试网址来保护这一点,然后如果没有安装youtube则使用safari.

将此密钥添加到info.plist

<key>LSApplicationQueriesSchemes</key>
<array>
   <string>youtube</string>
</array>
Run Code Online (Sandbox Code Playgroud)

然后,如果未安装Youtube应用程序,这是将回溯到safari的代码.

    let youtubeId = "vklj235nlw"
    var url = URL(string:"youtube://\(youtubeId)")!
    if !UIApplication.shared.canOpenURL(url)  {
        url = URL(string:"http://www.youtube.com/watch?v=\(youtubeId)")!
    }
    UIApplication.shared.open(url, options: [:], completionHandler: nil)
Run Code Online (Sandbox Code Playgroud)

  • 对于iOS 9,你还需要在`info.plist`中设置``LSApplicationQueriesSchemes`到一个包含`youtube`的数组http://stackoverflow.com/questions/40119595/canopenurl-not-working-in-ios-10 (3认同)

Gab*_*iel 15

你可以用这个:

UIApplication.sharedApplication().openURL("youtube://XXXXXX")
Run Code Online (Sandbox Code Playgroud)

其中XXXXXX是youtube中视频的代码.


Ibr*_*him 6

Swift 3和iOS 10+的更新

好的,有两个简单的步骤可以实现:

首先,你必须修改Info.plist到列表YoutubeLSApplicationQueriesSchemes。只需将其Info.plist作为源代码打开,然后粘贴即可:

<key>LSApplicationQueriesSchemes</key>
<array>
    <string>youtube</string>
</array>
Run Code Online (Sandbox Code Playgroud)

在这之后,你可以通过简单地替代打开任何YouTube网址里面的Youtube应用程序https://youtube://。这是完整的代码,您可以将此代码链接为操作中具有的任何按钮:

@IBAction func YoutubeAction() {

    let YoutubeID =  "Ktync4j_nmA" // Your Youtube ID here
    let appURL = NSURL(string: "youtube://www.youtube.com/watch?v=\(YoutubeID)")!
    let webURL = NSURL(string: "https://www.youtube.com/watch?v=\(YoutubeID)")!
    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)
    }

}
Run Code Online (Sandbox Code Playgroud)