NSURL 使用 mailto 抛出 nil 异常:

NSURL Throws nil exception using mailto:

我试图在 UILabel 单击事件中打开邮件。但它抛出致命错误:

unexpectedly found nil while unwrapping an Optional value.

使用的代码:

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)
    }

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

在使用 if let:

解包之前检查以确保 self.lblMail.text 不为零
if let email = self.lblMail.text {
    let url = NSURL(string: "mailto:\(email)")!
    UIApplication.sharedApplication().openURL(url)
}

如果出现错误:

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

确保您运行此代码是在实际设备上而不是iOS模拟器上。