如何使用MFMailComposeViewController与模拟器?

时间:2015-10-04 20:59:36

标签: ios-simulator swift2 mfmailcomposeviewcontroller

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

我的代码:

 <%= fields_for :user do |user|
    ...
 <% end %>

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

引发错误      打印(&#34;邮件已取消&#34;)

当我在我的设备(iPad)上测试时,一切都很好。但是当我使用模拟器时,我得到了错误

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)

但是我想在模拟器中运行它,看看它在iPhone 6上的外观......

1 个答案:

答案 0 :(得分:0)

您必须先检查设备是否可以使用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)
}