swiftios8ios-web-app

Swift make a phone call from the WebView


I'm trying to make a call from click on WebView but not work.

func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {

    if navigationType == UIWebViewNavigationType.LinkClicked {

        if (request.URL?.absoluteString!.rangeOfString("tel://") != nil) {

            var phone : String = request.URL!.absoluteString!

            println(phone)

            var url:NSURL? = NSURL(string: phone)
            UIApplication.sharedApplication().openURL(url!)

            return false

        } else {

            return true

        }
    }

    return true
}

Thanks in advance!


Solution

  • This is untested but I think you could do something like:

    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        if navigationType == UIWebViewNavigationType.LinkClicked {
            let application = UIApplication.sharedApplication()
            if let phoneURL = request.URL where (phoneURL.absoluteString!.rangeOfString("tel://") != nil) {
                if application.canOpenURL(phoneURL) {
                    application.openURL(phoneURL)
                    return false
                }
            }
        } 
        return true
    }
    

    You should note that this will not work on the Simulator as application.canOpenURL(phoneURL) will return false. This will only work on an actual iPhone.