How to open mail app from Swift

前端 未结 15 1290
被撕碎了的回忆
被撕碎了的回忆 2020-11-30 20:18

Im working on a simple swift app where the user inputs an email address and presses a button which opens the mail app, with the entered address in the address bar. I know ho

15条回答
  •  既然无缘
    2020-11-30 20:51

    I'm not sure if you want to switch to the mail app itself or just open and send an email. For the latter option linked to a button IBAction:

        import UIKit
        import MessageUI
    
        class ViewController: UIViewController, MFMailComposeViewControllerDelegate {
    
        @IBAction func launchEmail(sender: AnyObject) {
    
        var emailTitle = "Feedback"
        var messageBody = "Feature request or bug report?"
        var toRecipents = ["friend@stackoverflow.com"]
        var mc: MFMailComposeViewController = MFMailComposeViewController()
        mc.mailComposeDelegate = self
        mc.setSubject(emailTitle)
        mc.setMessageBody(messageBody, isHTML: false)
        mc.setToRecipients(toRecipents)
    
        self.presentViewController(mc, animated: true, completion: nil)
        }
    
        func mailComposeController(controller:MFMailComposeViewController, didFinishWithResult result:MFMailComposeResult, error:NSError) {
            switch result {
            case MFMailComposeResultCancelled:
                print("Mail cancelled")
            case MFMailComposeResultSaved:
                print("Mail saved")
            case MFMailComposeResultSent:
                print("Mail sent")
            case MFMailComposeResultFailed:
                print("Mail sent failure: \(error?.localizedDescription)")
            default:
                break
            }
            self.dismissViewControllerAnimated(true, completion: nil)
        }
    
        }
    

提交回复
热议问题