SwiftUI check if URL is reachable and switch to ContentView automaticly

856 views Asked by At

I tried this to check the status of connectivity :

func checkConnection() {
if let url = URL(string: "https://www.xxxxxxxxxxxxxxxxxxxxx") {
    var request = URLRequest(url: url)
    request.httpMethod = "HEAD"
    URLSession(configuration: .default)
      .dataTask(with: request) { (_, response, error) -> Void in
        guard error == nil else {
          print("Error:", error ?? "")
          return
        }

        guard (response as? HTTPURLResponse)?
          .statusCode == 200 else {
            print("down")

            return
        }

        print("up")

        
        
      }
      .resume()
  }
}

and it works fine. It shows "up" or "down" in console. I'm a beginner in Xcode and SwiftUI, so my question is: Instead of print("up") I want to go automaticly to the "ContentView" if URL is reachable. I tried ContentView() but it does not work.

Thanks for your help.

1

There are 1 answers

0
xTwisteDx On

This is easily handled with a NavigationLink. One method to do this is by doing the following.

Add a binding to keep state for if the view is active. Add navigation link to present the view that you want. Check your conditions returning true/false If condition is true, the bound state will update the NavigationLink and view will be presented.

@State var isValidURL = false

//Body {...

NavigationLink(destination: ContentView(), isActive: isValidURL {}


func checkConnection() {
if let url = URL(string: "https://www.xxxxxxxxxxxxxxxxxxxxx") {
    var request = URLRequest(url: url)
    request.httpMethod = "HEAD"
    URLSession(configuration: .default)
      .dataTask(with: request) { (_, response, error) -> Void in
        guard error == nil else {
          print("Error:", error ?? "")
          return
        }

        guard (response as? HTTPURLResponse)?
          .statusCode == 200 else {
            print("down")

            return
        }

        self.isValidURL.toggle()
      }
      .resume()
  }
}