3

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!) // joe@nts.com is here
        let url = NSURL(string: "mailto:\(self.lblMail.text)")! //url is nil when debugged
        UIApplication.sharedApplication().openURL(url)
    }
JAL
  • 41,701
  • 23
  • 172
  • 300
user2695433
  • 2,013
  • 4
  • 25
  • 44

2 Answers2

3

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.

JAL
  • 41,701
  • 23
  • 172
  • 300
0

Try let url = NSURL(string: "mailto:\(self.lblMail.text!)")!

Andrey Chernukha
  • 21,488
  • 17
  • 97
  • 161