Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to launch the iOS mail app in Swift?

I'm creating an iOS application with a password reset feature that sends an email to the user. After sending the email I want to display a UIAlertController to the user asking them if they would like to open the mail application.

I've seen various posts on here along the lines of:

let url = NSURL(string: "mailto:")
UIApplication.sharedApplication().openURL(url!)

This works but unfortunately it starts a new message which is not what I want. I only want to launch the application so the user can see their inbox.

like image 439
Kyle Decot Avatar asked Apr 02 '15 21:04

Kyle Decot


2 Answers

Not tested myself but maybe this answer will help you:

Apparently Mail supports a second url scheme message:// which (I suppose) allows you to open a specific message if it was fetched by your application. If you do not provide a full message url, it will just open Mail:

let mailURL = URL(string: "message://")!
if UIApplication.shared.canOpenURL(mailURL) {
    UIApplication.shared.openURL(mailURL)
}

Taken from: Launch Apple Mail App from within my own App?

like image 53
dehlen Avatar answered Oct 21 '22 14:10

dehlen


The Swift 3.0.1 way of just opening the Mail app goes as follows:

private func openMailClient() {
    let mailURL = URL(string: "message://")!
    if UIApplication.shared.canOpenURL(mailURL) {
        UIApplication.shared.openURL(mailURL)
    }
}

As "dehlen" correctly stated, using the message:// scheme will only open the mail app, if no further information is provided.

like image 25
Philipp Jahoda Avatar answered Oct 21 '22 14:10

Philipp Jahoda