14

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

Marcus Ziadé
  • 650
  • 2
  • 7
  • 17

5 Answers5

35

iOS 14.0+

Using Link:

Link("Some label", destination: URL(string: "https://www.mylink.com")!)

Older versions

Button(action: {
    if let url = URL(string: "https://www.mylink.com") {
       UIApplication.shared.open(url)
    }
}) {
    Text("Some label")
}
Alexander Sandberg
  • 1,265
  • 11
  • 19
cbear84
  • 486
  • 4
  • 13
3

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

Richard Topchii
  • 7,075
  • 8
  • 48
  • 115
2

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)
jfuellert
  • 550
  • 4
  • 10
0

This can be done through SwiftUI's Link: https://developer.apple.com/documentation/swiftui/link.

Curiosity
  • 544
  • 1
  • 15
  • 29
0

In SwiftUI, you can use Link. For example:

Link("Link Text", destination: URL(string: "https://www.example.com/page.html")!)

Adam Neuwirth
  • 529
  • 5
  • 10