'How do I use a mailto link in Text() in swift 5, SwiftUI [duplicate]
There are dozens of Stackoverflow answers for mailto links in Swift 5.
The consensus look like this
let url = NSURL(string: "mailto:[email protected]")
UIApplication.sharedApplication().openURL(url)
But how do I actually use this code? Ideally in an alert, but at least a general Text element
import SwiftUI
struct MainMenu: View {
@State private var showAlert = false
// What do I put here
var emailLink:UIApplication {
let url = URL(string: "mailto:[email protected]")!
return UIApplication.shared.openURL(url)
}
// To make it work in here
var body: some View {
HStack(alignment: .center, spacing: .zero, content: {
Text(
"Here is an email link \(emailLink)"
)
Button(action: {
showAlert = true
}) {
Text("MENU")
}
.alert(isPresented: $showAlert, content: {
Alert(
title: Text("Title Here"),
message: Text(
"Need Help, \(emailLink)"
)
)
})
})
}
}
Solution 1:[1]
You can use Environment var openURL for this, documentation here.
struct ContentView: View {
@Environment(\.openURL) var openURL
@State var alert: Bool = false
var body: some View {
HStack {
Button(action: {
alert.toggle()
}, label: {
Label("Email", systemImage: "envelope.fill")
})
}
.alert("Contact", isPresented: $alert, actions: {
Button(action: {
mailto("[email protected]")
}, label: {
Label("Email", systemImage: "envelope.fill")
})
Button("Cancel", role: .cancel, action: {})
})
}
func mailto(_ email: String) {
let mailto = "mailto:\(email)".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
print(mailto ?? "")
if let url = URL(string: mailto!) {
openURL(url)
}
}
}
Solution 2:[2]
Without an Alert, based on the suggestive comment of George this works:
var body: some View {
Text(
"Here is an email link "
)
Link("[email protected]", destination: URL(string: "mailto:[email protected]")!)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 |

