-1

After a user in my app registers, they are taken to a static screen until they verify their email. This screen contains a button that when pressed, is supposed to open the IOS mail app. How do I do this in SwiftUI?

I'm aware that I can send an email with UIApplication.shared.open(URL(string: "mailto:...")) but I'm trying to specifically just open the app. I've tried googling but all the tutorials I've seen are for sending emails.

corbiter
  • 47
  • 6
  • 3
    Does this answer your question? [Launch Apple Mail App from within my own App?](https://stackoverflow.com/questions/8821934/launch-apple-mail-app-from-within-my-own-app) – CloudBalancing Feb 25 '22 at 04:26

2 Answers2

1

Thanks to @CloudBalancing for finding the link. The url to open the mail app is URL(string: "message://").

func openMail() {
    let url = URL(string: "message://")
    if let url = url {
        if UIApplication.shared.canOpenURL(url) {
            UIApplication.shared.open(url, options: [:], completionHandler: nil)
        }
    }
}
corbiter
  • 47
  • 6
1
func openMail(emailTo:String, subject: String, body: String) {
    if let url = URL(string: "mailto:\(emailTo)?subject=\(subject.fixToBrowserString())&body=\(body.fixToBrowserString())"),
       UIApplication.shared.canOpenURL(url)
    {
        UIApplication.shared.open(url, options: [:], completionHandler: nil)
    }
}

extension String {
    func fixToBrowserString() -> String {
        self.replacingOccurrences(of: ";", with: "%3B")
            .replacingOccurrences(of: "\n", with: "%0D%0A")
            .replacingOccurrences(of: " ", with: "+")
            .replacingOccurrences(of: "!", with: "%21")
            .replacingOccurrences(of: "\"", with: "%22")
            .replacingOccurrences(of: "\\", with: "%5C")
            .replacingOccurrences(of: "/", with: "%2F")
            .replacingOccurrences(of: "‘", with: "%91")
            .replacingOccurrences(of: ",", with: "%2C")
            //more symbols fixes here: https://mykindred.com/htmlspecialchars.php
    }
}

if you have some issues with opening of the email link - probably you need to add addidtional fixes to function fixToBrowserString()

usage in SwiftUI:

Button("Support Email") { 
    openMail(emailTo: "support@gmail.com", 
             subject: "App feedback", 
             body: "Huston, we have a problem!\n\n...")
}
Andrew_STOP_RU_WAR_IN_UA
  • 9,318
  • 5
  • 65
  • 101