web-dev-qa-db-fra.com

MFMailComposeViewController dans Swift

Voici un exemple de code:

import UIKit
import MessageUI

class ViewController: UIViewController, MFMailComposeViewControllerDelegate {

    @IBAction func showEmail(sender : AnyObject) {
        var emailTitle = "Test Email"
        var messageBody = "This is a test email body"
        var toRecipents = ["[email protected]"]
        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)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    func mailComposeController(controller:MFMailComposeViewController, didFinishWithResult result:MFMailComposeResult, error:NSError) {
        switch result {
        case MFMailComposeResultCancelled:
            NSLog("Mail cancelled")
        case MFMailComposeResultSaved:
            NSLog("Mail saved")
        case MFMailComposeResultSent:
            NSLog("Mail sent")
        case MFMailComposeResultFailed:
            NSLog("Mail sent failure: %@", [error.localizedDescription])
        default:
            break
        }
        self.dismissViewControllerAnimated(false, completion: nil)
    }
}

Dans la fonction mailComposeController, j'obtiens une erreur sur chaque cas expression:

Impossible de trouver une surcharge '~ =' qui accepte les arguments fournis.

Qu'est-ce que je fais mal?

29
Alexey Nakhimov

J'ai comparé la documentation de MFMailComposeResult sur Xcode 5 et Xcode 6. Dans Swift, MFMailComposeResult est une structure

struct MFMailComposeResult {
    init(_ value: CUnsignedInt) // available in iPhone 3.0
    var value: CUnsignedInt
}

avec MFMailComposeResultCancelled comme constante de type MFMailComposeResult:

var MFMailComposeResultCancelled: MFMailComposeResult { get }

alors que c'est une énumération dans Objective-C:

 enum MFMailComposeResult {
    MFMailComposeResultCancelled,
    MFMailComposeResultSaved,
    MFMailComposeResultSent,
    MFMailComposeResultFailed
};
typedef enum MFMailComposeResult MFMailComposeResult;   // available in iPhone 3.0

Afin de faire fonctionner votre code, vous devrez comparer leurs valeurs qui sont CUnsignedInt.

Vous devrez donc taper le code suivant:

func mailComposeController(controller:MFMailComposeViewController, didFinishWithResult result:MFMailComposeResult, error:NSError) {
    switch result.value {
    case MFMailComposeResultCancelled.value:
        println("Mail cancelled")
    case MFMailComposeResultSaved.value:
        println("Mail saved")
    case MFMailComposeResultSent.value:
        println("Mail sent")
    case MFMailComposeResultFailed.value:
        println("Mail sent failure: \(error.localizedDescription)")
    default:
        break
    }
    self.dismissViewControllerAnimated(false, completion: nil)
}
31

dans Swift 2.0 faites ceci:

func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?) {
        switch result.rawValue {
        case MFMailComposeResultCancelled.rawValue:
            print("Mail cancelled")
        case MFMailComposeResultSaved.rawValue:
            print("Mail saved")
        case MFMailComposeResultSent.rawValue:
            print("Mail sent")
        case MFMailComposeResultFailed.rawValue:
            print("Mail sent failure: \(error!.localizedDescription)")
        default:
            break
        }
        controller.dismissViewControllerAnimated(true, completion: nil)
    }
19
David

Dans Swift 3.0 -> Changement de syntaxe

func mailComposeController(controller: MFMailComposeViewController,
                           didFinishWithResult result: MFMailComposeResult, error: NSError?) {

    switch result.rawValue {
    case MFMailComposeResult.Cancelled.rawValue:
        print("Mail cancelled")
    case MFMailComposeResult.Saved.rawValue:
        print("Mail saved")
    case MFMailComposeResult.Sent.rawValue:
        print("Mail sent")
    case MFMailComposeResult.Failed.rawValue:
        print("Mail sent failure: %@", [error!.localizedDescription])
    default:
        break
    }
    // Dismiss the mail compose view controller.
    controller.dismissViewControllerAnimated(true, completion: nil)
}
6
Dipang

Dans Swift 3, vous pouvez utiliser ce code clair:

 @IBAction func sendMail(_ sender: Any) {

        print(MFMailComposeViewController.canSendMail())
        if MFMailComposeViewController.canSendMail() {
            let mail = MFMailComposeViewController()
            mail.mailComposeDelegate = self
            mail.setToRecipients(["[email protected]"])
            mail.setMessageBody("<p>This is test Mail!</p>", isHTML: true)

            present(mail, animated: true)
        } else {
             let email = "[email protected]"
             if let url = URL(string: "mailto:\(email)") {
             UIApplication.shared.open(url)
             }

        }


    }

    func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
        controller.dismiss(animated: true)
        switch result {
        case .cancelled:
            print("Mail cancelled")
        case .saved:
            print("Mail saved")
        case .sent:
            self.allertInfo(_title: "Mail Info", _message: "Mail is sent successfuly", _actionTitle: "OK")
            print("Mail sent")
        case .failed:
            self.allertInfo(_title: "Mail Info", _message: "Mail isn't sent.",
_actionTitle: "OK")
            print("Mail sent failure: \(error?.localizedDescription)")
        default:
            break
        }

    }

    func allertInfo(_title:String, _message:String, _actionTitle:String) {

        let alert = UIAlertController(title: _title, message: _message, preferredStyle: UIAlertControllerStyle.alert)
        alert.addAction(UIAlertAction(title: _actionTitle, style: UIAlertActionStyle.default, handler: nil))
        self.present(alert, animated: true, completion: nil)

    }
1
Yasin Ugurlu