更改默认电子邮件应用程序是否会影响 MFMailComposeViewController 的使用?

Does changing the default email app affect MFMailComposeViewController usage?

iOS 14 个用户可以更改默认电子邮件应用程序。这对 MFMailComposeViewController 有什么影响(如果有的话)?更具体地说,如果 MFMailComposeViewController 与任何默认电子邮件客户端“正常工作”将是理想的,例如设置收件人、主题、正文等。

如果这不可能,我想打开一个 mailto URL 将打开任何默认的邮件应用程序。在 iOS 14 个版本之前有什么方法可以测试这个?

iOS 14 及其设置默认邮件应用程序的能力在 MFMailComposeViewController API 方面没有任何改变。它只能显示邮件的撰写 sheet,因此当他们不使用邮件应用程序时,canSendMail() 仍将 return false

为了更好地支持选择使用其他电子邮件应用程序的用户,您可以打开 mailto URL。这将打开默认的电子邮件应用程序并调出他们的撰写 sheet。如果没有安装电子邮件应用程序,它将显示一个系统警报,询问用户是否要从 App Store 恢复邮件(除非在模拟器中 运行)。此 API doc 解释了如何创建 URL,包括如何指定主题、正文和其他收件人。

请注意,这将使您的应用程序无法打开“邮件”应用程序或其他电子邮件应用程序。如果您想让用户在使用邮件时留在您的应用中,您可以继续使用 MFMailComposeViewController 并在 canSendMail() returns false.

如果您愿意,您可以另外检查是否可以打开 mailto: URL,如果不能,则向用户显示您自己的消息。请注意,这需要您将 mailto 添加到 Info.plist 中的 LSApplicationQueriesSchemes

我发现这个 post 也很有用。

if MFMailComposeViewController.canSendMail() {
    let mail = MFMailComposeViewController()
    mail.mailComposeDelegate = self
    mail.setToRecipients([email])
    mail.setSubject(subject)
    present(mail, animated: true, completion: nil)
} else {
    if let mailURLString = "mailto:\(email)?subject=\(subject)".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed),
       let mailURL = URL(string: mailURLString) {
        if UIApplication.shared.canOpenURL(mailURL) { //check not needed, but if desired add mailto to LSApplicationQueriesSchemes in Info.plist
            view.window?.windowScene?.open(mailURL, options: nil, completionHandler: nil)
        } else {
            //maybe they like web apps? ‍♂️ 
            //maybe let them copy the email address to the clipboard or something
        }
    }
}