Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSURL Throws nil exception using mailto:

I was trying to open mail on UILabel click event. But its throws fatal error:

unexpectedly found nil while unwrapping an Optional value.

Code used:

func sendMail(sender:UITapGestureRecognizer){
        print("mail::" + self.lblMail.text!) // [email protected] is here
        let url = NSURL(string: "mailto:\(self.lblMail.text)")! //url is nil when debugged
        UIApplication.sharedApplication().openURL(url)
    }
like image 947
user2695433 Avatar asked Nov 23 '25 17:11

user2695433


1 Answers

Check to make sure self.lblMail.text is non-nil before proceeding by unwrapping it with an if let:

if let email = self.lblMail.text {
    let url = NSURL(string: "mailto:\(email)")!
    UIApplication.sharedApplication().openURL(url)
}

If you get the error:

LaunchServices: ERROR: There is no registered handler for URL scheme mailto

Make sure you're running this code on an actual device and not the iOS Simulator.

like image 152
JAL Avatar answered Nov 25 '25 11:11

JAL