【发布时间】:2016-04-16 22:26:03
【问题描述】:
我有一个UIWebView,它加载了一个本地 index.html 文件。
但是我在这个 html 文件中有一个外部链接,我想在 Safari 中打开,而不是在 UIWebView 内部打开。
从UIButton 说在 Safari 中打开一个链接很简单:
UIApplication.sharedApplication().openURL(NSURL(string: "http://www.stackoverflow.com"))
从外部链接打开 Instagram 应用程序也很有效。
<a href="instagram://media?id=434784289393782000_15903882">instagram://media?id=434784289393782000_15903882</a>
所以我的第一个想法是做这样的事情:
<a href="safari://stackoverflow.com">Open in Safari</a>
但这似乎不起作用,然后我阅读了一些关于使用webView:shouldStartLoadWithRequest:navigationType:的内容
但是所有在 Safari 中打开外部链接的人都在使用 Obj-C 编写,因为我在使用 Swift 编写时不太熟悉。
使用 Swift 代码更新:
import UIKit
class AccessoriesViewController: UIViewController, UIWebViewDelegate {
@IBOutlet weak var webView:UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
if let url = NSBundle.mainBundle().URLForResource("accessories", withExtension: "html") {
webView.loadRequest(NSURLRequest(URL: url))
}
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return UIStatusBarStyle.LightContent;
}
func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
if let url = request.URL where navigationType == UIWebViewNavigationType.LinkClicked {
UIApplication.sharedApplication().openURL(url)
return false
}
return true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
【问题讨论】:
标签: html ios swift safari uiwebview