Mal*_*ito 5 email message ios swift swiftui
我目前正在尝试使用 SwiftUI 生命周期并针对 iOS 14 在我的 SwiftUI 应用程序中实现“发送电子邮件”按钮。
我知道网上有很多解决方案 - 这里是堆栈溢出和其他地方。但是,到目前为止,我还无法在模拟器/设备上进行任何操作。
我当前的解决方案如下所示(基于stackoverflow 上的这个问题:
import SwiftUI
import MessageUI
import Foundation
struct ContentView: View {
class MailComposeViewController: UIViewController, MFMailComposeViewControllerDelegate {
static let shared = MailComposeViewController()
func sendEmail() {
if MFMailComposeViewController.canSendMail() {
let mail = MFMailComposeViewController()
mail.mailComposeDelegate = self
mail.setToRecipients(["test@test.com"])
UIApplication.shared.windows.last?.rootViewController?.present(mail, animated: true, completion: nil)
} else {
// Alert
}
}
func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
controller.dismiss(animated: true, completion: nil)
}
}
var body: some View {
Button(action: {
MailComposeViewController.shared.sendEmail()
}, label: {
Text("Send")
})
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Run Code Online (Sandbox Code Playgroud)
模拟器确实显示了按钮并且没有给我任何错误。然而,点击按钮后,什么也没有发生——在设备上测试时也是同样的情况。
知道这里可能出了什么问题吗?
谢谢!
以我原来的问题中共享的代码片段为基础:
根据 @Arjun 的回答,这是我当前的解决方法,用于解决有人可能已删除 Apple Mail 应用程序并正在使用其他电子邮件应用程序的边缘情况:
Button(action: {
if MailComposeViewController.shared.canSendMail() {
MailComposeViewController.shared.sendEmail()
} else {
openURL(URL(string: "mailto:someone@example.com?subject=This%20is%20the%20subject")!)
}
}, label: {
Text("Send")
})
Run Code Online (Sandbox Code Playgroud)
只要用户设置了 Apple Mail,它就会打开应用程序内工作表,否则会使用 mailto: 链接切换到任何其他电子邮件应用程序。
| 归档时间: |
|
| 查看次数: |
2597 次 |
| 最近记录: |