我有显示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)
}
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>
这很完美,但我也想让用户在 youtube 应用程序上观看它。是否可以在网络视图中创建启动YouTube应用程序的链接(如果安装在设备上)?
任何帮助表示赞赏。
由于 Youtube 没有预装在手机上,因此最好通过测试 URL 来保护这一点,然后回退到使用 safari(如果他们没有安装 youtube)。
将此键添加到您的 info.plist
<key>LSApplicationQueriesSchemes</key>
<array>
<string>youtube</string>
</array>
然后,如果未安装 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)
你可以使用这个:
UIApplication.sharedApplication().openURL("youtube://XXXXXX")
其中XXXXXX是YouTube中视频的代码。
适用于 Swift 3 和 iOS 10+ 的更新
好的,有两个简单的步骤可以实现此目的:
首先,您必须修改Info.plist
以列出带有LSApplicationQueriesSchemes
的Youtube
。只需打开Info.plist
作为源代码,然后粘贴以下内容:
<key>LSApplicationQueriesSchemes</key>
<array>
<string>youtube</string>
</array>
之后,您只需将https://
替换为 youtube://
即可在 Youtube 应用程序中打开任何 Youtube URL。这是一个完整的代码,您可以将此代码链接到您作为操作的任何按钮:
@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)
}
}
Swift 3
UIApplication.shared.openURL(URL(string: "http://youtube.com")!)
如果未安装 YouTube 应用,则会打开 Safari(网页)