I have build a Swift
iOS app with the only purpose to display a website with the help of WKWebView.
This works fine, but pressing on links (e.g. on an [mailto:]
button) doesn't work because it can't open anything!
Does anybody have a solution for this?
I have read a lot about solving this, but I don't know where to start.
Thanks for the help
[UPDATE: ]
The code below shows the solution
import UIKit
import WebKit
class ViewController: UIViewController, WKNavigationDelegate {
@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()
webView?.navigationDelegate = self
let url = NSURL(string:"https://google.de")
let req = NSURLRequest (URL: url!)
self.webView!.loadRequest(req)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func prefersStatusBarHidden() -> Bool {
return true
}
func webView(webView: WKWebView, decidePolicyForNavigationAction navigationAction: WKNavigationAction, decisionHandler: (WKNavigationActionPolicy) -> Void) {
let url = navigationAction.request.URL?.absoluteString
let url_elements = url!.componentsSeparatedByString(":")
switch url_elements[0] {
case "mailto":
openCustomApp("mailto://", additional_info: url_elements[1])
decisionHandler(.Cancel)
default:
}
decisionHandler(.Allow)
}
func openCustomApp(urlScheme:String, additional_info:String){
if let requestUrl:NSURL = NSURL(string:"\(urlScheme)"+"\(additional_info)") {
let application:UIApplication = UIApplication.sharedApplication()
if application.canOpenURL(requestUrl) {
application.openURL(requestUrl)
}
}
}
}
You have to implement the following method (part of WebKit), which can be used to parse such URLs:
func webView(webView: WKWebView, decidePolicyForNavigationAction navigationAction: WKNavigationAction, decisionHandler: (WKNavigationActionPolicy) -> Void)
The idea is to write if-statements to check for certain URL types before passing the decision. More info here:
Keep in mind that some of the syntax for delegates has changed slightly in Swift 3 - something to keep in mind when using tutorials. If you have already found this but you ran into an error - post your code.
EDIT: just an update for others who stumble upon this question. Keep in mind that you need the right formatting for mailto e.g. mailto://[email protected]
(as mentioned by OhadM in the comments of the OP)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With