swift2 如何在模拟器中使用MFMailComposeViewController?

kadbb459  于 2022-11-06  发布在  Swift
关注(0)|答案(1)|浏览(161)

我想在Swift 2.0和Xcode 7.0.1中使用一个MFMailComposeViewController()。我担心,这是一个重复的问题,但没有找到解决方案。
我的代码:

@IBAction func sendMail(sender: AnyObject) {
  let picker = MFMailComposeViewController()
  picker.mailComposeDelegate = self
  picker.setSubject(subject.text!)
  picker.setMessageBody(body.text, isHTML: true)
  presentViewController(picker, animated: true, completion: nil)
}

func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?) {
   switch result.rawValue {
   case MFMailComposeResultCancelled.rawValue:
       print("Mail cancelled")
   case MFMailComposeResultSaved.rawValue:
       print("Mail saved")
  case MFMailComposeResultSent.rawValue:
       print("Mail sent")
  case MFMailComposeResultFailed.rawValue:
       print("Mail sent failure: \(error!.localizedDescription)")
  default:
      break
 }
 dismissViewControllerAnimated(true, completion: nil)

打印时抛出错误(“Mail cancelled”(邮件取消))
当我在我的设备(iPad)上测试这个时,一切都很好。但是当我使用模拟器时,我得到了错误

viewServiceDidTerminateWithError: Error          
 Domain=_UIViewServiceInterfaceErrorDomain Code=3 "(null)" 
 UserInfo={Message=Service Connection Interrupted}
 Mail cancelled

但是我想在模拟器中运行这个,看看它在iPhone 6上看起来如何...

z6psavjg

z6psavjg1#

您必须首先检查设备是否可以使用MFMailComposeViewController.canSendMail()发送邮件

@IBAction func sendMail(sender: AnyObject) {
    guard MFMailComposeViewController.canSendMail()
        else { 
            // TODO: Alert the user its device cannot send mail
            print("Mail services are not available")
            return 
    } 

    let picker = MFMailComposeViewController()
    picker.mailComposeDelegate = self
    picker.setSubject(subject.text!)
    picker.setMessageBody(body.text, isHTML: true)
    presentViewController(picker, animated: true, completion: nil)
}

相关问题