UIButton没有提出MFMailViewController

时间:2017-02-21 22:24:00

标签: swift mfmailcomposeviewcontroller mfmailcomposer messageui

我的代码有点错误。我是新手,我正在努力教自己。我在网上找到了大部分答案,但似乎无法找到有关此特定问题的任何内容。我想在应用程序中发送一封电子邮件,但只要我按下电子邮件按钮,MFMailViewController就不会出现。这就像我的UIButton无法正常工作。但我知道我把它作为IBAction。到目前为止,这是我的代码。非常感谢任何帮助。

import UIKit
import MessageUI

class RequestService: UIViewController,MFMailComposeViewControllerDelegate {
    @IBOutlet weak var CustomerName: UITextField!
    @IBOutlet weak var emailButton: UIButton!

    @IBAction func sendEmail(_ sender: UIButton) {
        if !MFMailComposeViewController.canSendMail() {
            print("Mail services are not available")

            let ComposeVC = MFMailComposeViewController()
            ComposeVC.mailComposeDelegate = self

            ComposeVC.setToRecipients(["jwelch@ussunsolar.com"])
            ComposeVC.setSubject("New Support Ticket")
            ComposeVC.setMessageBody(CustomerName.text!, isHTML: false)

            self.present(ComposeVC, animated: true, completion: nil)
        }

        func mailComposeController(controller: MFMailComposeViewController,didFinishWithResult result:MFMailComposeResult, error: NSError?) {
            // Check the result or perform other tasks.
            // Dismiss the mail compose view controller.
            controller.dismiss(animated: true, completion: nil)
        }
    }
}

2 个答案:

答案 0 :(得分:0)

如果设备无法发送电子邮件,您只会尝试显示邮件控制器。那是倒退。

@IBAction func sendEmail(_ sender: UIButton) {
    if MFMailComposeViewController.canSendMail() {
        print("Mail services are not available")

        let ComposeVC = MFMailComposeViewController()
        ComposeVC.mailComposeDelegate = self

        ComposeVC.setToRecipients(["jwelch@ussunsolar.com"])
        ComposeVC.setSubject("New Support Ticket")
        ComposeVC.setMessageBody(CustomerName.text!, isHTML: false)

        self.present(ComposeVC, animated: true, completion: nil)
    }
}

func mailComposeController(controller: MFMailComposeViewController,didFinishWithResult result:MFMailComposeResult, error: NSError?) {
    // Check the result or perform other tasks.
    // Dismiss the mail compose view controller.
    controller.dismiss(animated: true, completion: nil)
}

你需要在另一种方法之外的委托方法。

答案 1 :(得分:0)

您在sendMail函数的语法中出错了。您发布的代码仅在设备无法发送邮件时才会打开视图控制器。将其更改为:

@IBAction func sendEmail(_ sender: UIButton) {
    if !MFMailComposeViewController.canSendMail() {
        print("Mail services are not available")
        return
    }

    let composeVC = MFMailComposeViewController()
    composeVC.mailComposeDelegate = self
    composeVC.setToRecipients(["jwelch@ussunsolar.com"])
    composeVC.setSubject("New Support Ticket")
    composeVC.setMessageBody(CustomerName.text!, isHTML: false)

    self.present(composeVC, animated: true, completion: nil)
}