Open mailto link from UIWebView

Hi everyone I am trying to develop a webView application. Inside my webview I have a mailto link and I want to open it outside the webview on the mail application of iOS.

This is my code

  func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool{
        print("stampa richiesta : ")
        print(request)
              var stringaURL = ""
      /
            stringaURL = try! String(contentsOf: request.url!, encoding: String.Encoding.ascii)
      /
        /
        /


        if navigationType == UIWebViewNavigationType.linkClicked{
            if((stringaURL.range(of:"www.collegiodeirettori.net/palio/")) != nil ){
              print("stampa richiesta : ")
                print(request)
            }
            else{
                print("stampa richiesta : ")
                print(request)
                UIApplication.shared.openURL(request.url!)
                    /
                    return false;
         
         
            }
     


        }

        return true;

}

I already made a func that control if a link have to be opened in safari and that works but no for the mailto link.. Any ideas? Thanks!

This is the error that report when I click on mailto link :

fatal error: 'try!' expression unexpectedly raised an error: Error Domain=NSCocoaErrorDomain Code=256 "The file couldn’t be opened." UserInfo={NSURL=mailto:turismo@comune.asti.it}:


Any

Replies

Your

String(contentsOf:encoding:)
code is trying to read the content of the URL, which makes sense for file URLs, HTTP URLs, and so on, but makes no sense for
mailto
URLs. If you want to get a string representation of the URL, use the
absoluteString
property.

Or, better yet, learn to love

URLComponents
, which lets you look at the parts of the URL without having to do string parsing. For example:
let url = URL(string: "mailto:turismo@comune.asti.it")!
if let uc = URLComponents(url: url, resolvingAgainstBaseURL: true) {
    print(uc.scheme ?? "nil")  // -> mailto
    print(uc.path)              // -> turismo@comune.asti.it
}

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"