情景复现
给我的iOS应用“存钱猪猪”写用户反馈功能时,想要实现使用Swift发送邮件的功能,主要是给一个用户的反馈渠道,而且这个反馈渠道很多应用都在使用。
配置MessageUI
首先,打开Xcode并点击左侧的项目名称,找到TARGETS -> General -> Frameworks,Libraries,and Embedded Content,点击添加按钮。
输入“MessageUI”,可以在下面找到
MessageUI.framework
然后添加到我们的项目中。
实现代码
代码层面则需要创建一个结构体MailComposeViewController
import SwiftUI
import MessageUI
struct MailComposeViewController: UIViewControllerRepresentable {
typealias UIViewControllerType = MFMailComposeViewController
var recipients: [String]
var subject: String
var body: String
var resultCallback: ((MFMailComposeResult) -> Void)?
class Coordinator: NSObject, MFMailComposeViewControllerDelegate {
var parent: MailComposeViewController
init(parent: MailComposeViewController) {
self.parent = parent
}
func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
parent.resultCallback?(result)
controller.dismiss(animated: true)
}
}
func makeCoordinator() -> Coordinator {
return Coordinator(parent: self)
}
func makeUIViewController(context: Context) -> MFMailComposeViewController {
let vc = MFMailComposeViewController()
vc.mailComposeDelegate = context.coordinator
vc.setToRecipients(recipients)
vc.setSubject(subject)
vc.setMessageBody(body, isHTML: false)
return vc
}
func updateUIViewController(_ uiViewController: MFMailComposeViewController, context: Context) {}
}
View文件
import SwiftUI
import UIKit
import MessageUI
struct ContentView: View {
@State private var showMailComposer = false
@State private var mailResult: MFMailComposeResult?
var body: some View {
VStack {
// 问题反馈按钮
MenuItem(menuItem: MenuItemModel(iconName: "questionmark.circle", title: Feedback, action: {
self.showMailComposer = true // 调取邮件Sheet页
}))
}
// 邮件Sheet页
.sheet(isPresented: $showMailComposer) {
MailComposeViewController(
recipients: ["fangjunyu.com@gmail.com"], // 配置邮件地址
subject: "Feedback", // 配置邮件主题
body: "Hi fangjunyu,\n\n", // 配置邮件内容
resultCallback: { result in
self.mailResult = result
self.showMailComposer = false
})
}
}
}
#Preview {
ContentView(showSheet: .constant(true),showSettings: .constant(true))
}
在View中,我们需要引入MessageUI,配置两个变量,在问题反馈按钮中配置
self.showMailComposer = true
以及在我们的邮件弹出Sheet页中配置我们要发送的邮件内容。