I want a button inside my app, that will open safari and a specific URL address. How do I do this? UIApplication.sharedApplication doesn't seem to work in SwiftUI.
This is my first question here. Please give feedback if I did something wrong
I want a button inside my app, that will open safari and a specific URL address. How do I do this? UIApplication.sharedApplication doesn't seem to work in SwiftUI.
This is my first question here. Please give feedback if I did something wrong
Using Link:
Link("Some label", destination: URL(string: "https://www.mylink.com")!)
Button(action: {
if let url = URL(string: "https://www.mylink.com") {
UIApplication.shared.open(url)
}
}) {
Text("Some label")
}
In the View:
@Environment(\.openURL) private var openURL
Later, e.g. on button press:
guard let url = URL(string: urlString) else { return }
openURL(url)
Read more: https://developer.apple.com/documentation/swiftui/openurlaction
If you are using a SceneDelegate you can handle URL addresses using the following:
func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
guard let url = URLContexts.first?.url else {
return
}
//Handle URL here
}
From there you can call openURL like you normally would:
UIApplication.shared.open(url, options: [:], completionHandler: nil)
This can be done through SwiftUI's Link
: https://developer.apple.com/documentation/swiftui/link.
In SwiftUI, you can use Link. For example:
Link("Link Text", destination: URL(string: "https://www.example.com/page.html")!)