I'm creating an app that uses WKWebView. Whenever a user clicks on a link in that webview, I want the link to open up in safari instead of inside the webview. I'm really new at coding, so please make it as easy as possible. I just need the code I need to add. Here's the code bellow:
import UIKit
import WebKit
class FirstViewController: UIViewController {
@IBOutlet var containerView: UIView! = nil
var webView: WKWebView?
override func loadView() {
super.loadView()
self.webView = WKWebView()
self.view = self.webView!
}
override func viewDidLoad() {
super.viewDidLoad()
var url = NSURL(string:"http://www.example.com/")
var req = NSURLRequest(url:url as! URL)
self.webView!.load(req as URLRequest)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
I'm using Xcode 8 and Swift 3
What you need to do here is set the navigation delegate on the web view (via the
navigationDelegate
property) and then implement the
webView(_:decidePolicyFor:decisionHandler:)
callback along the lines of what’s shown below.
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
if let url = navigationAction.request.url, … handle in Safari … {
decisionHandler(.cancel)
UIApplication.shared.openURL(url)
} else {
decisionHandler(.allow)
}
}
where the elided code decides whether
url
should go to Safari or be opened in the web view.
Share and Enjoy
—
Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware
let myEmail = "eskimo" + "1" + "@apple.com"