Search code examples
iosswiftwebkit

How do I open phone from tel: url link from WebKit iOS app using Swift


I am creating an iPhone app and in part using WebKit to display a web page in the app. Currently, when I click a button that is displayed on the website it should open the phone app (with a tel: link) and dial the number. Unfortunately in the app, it does nothing, however, it works fine in chrome/ safari.

I have tried to scour the internet and attempted several suggestions but nothing seems to do anything so far.

import UIKit
import WebKit

class ShopViewController: UIViewController, WKNavigationDelegate, WKUIDelegate {

    @IBOutlet weak var backButton: UIBarButtonItem!
    @IBOutlet weak var shopWebKit: WKWebView!
    override func viewDidLoad() {
        super.viewDidLoad()

        shopWebKit.navigationDelegate = self
        shopWebKit.uiDelegate = self

        // Do any additional setup after loading the view.
    }
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear( animated )

        let urlString:String = "https://www.somewebsite.com"
        let url:URL = URL(string: urlString)!
        let urlRequest:URLRequest = URLRequest(url: url)
        shopWebKit.load(urlRequest)

    }

    @IBAction func backButtonTapped(_ sender: Any) {
        if shopWebKit.canGoBack{
            shopWebKit.goBack()
        }
    }

    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        backButton.isEnabled = webView.canGoBack
    }

    func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
        if navigationAction.targetFrame == nil {
            webView.load(navigationAction.request)

        }
        return nil
    }
}

I am hoping to be able to click any tel: link button loaded in the WebKit and have it open the phone app and dial the number. Please help.


Solution

  • Try below code it's working fine swift5. first add 'navigationDelegate' to your WKWebView.

    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: (WKNavigationActionPolicy) -> Void) {
    
        switch navigationAction.request.url?.scheme {
        case "tel":
            UIApplication.shared.open(navigationAction.request.url!, options: [:], completionHandler: nil)
            decisionHandler(.cancel)
            break
        default:
            decisionHandler(.allow)
            break
        }
    }
    

    Note: try testing with actual device.