I'm wanting to present an alert message when a user doesn't have network connection.
I have a function that will make an API call for data and also checking if there is network connectivity to avoid a crash. I'm sort of stuck on the best approach from here.
Here's the call I make for onAppear to call the function
I thought I could put an if statement after (routes) in, but I never get to that far when there is no network connecvitiy.
I have a function that will make an API call for data and also checking if there is network connectivity to avoid a crash. I'm sort of stuck on the best approach from here.
Code Block func getRoutes(completion: @escaping ([Route]) -> ()) { //Post is data model let routeMonitor = NWPathMonitor() print("aMonitor is set") routeMonitor.pathUpdateHandler = { path in if path.status == .satisfied { print("We're connected! Let's grab route data") guard let url = URL(string: "<URL>") else { return print("the JSON data didn't match") } URLSession.shared.dataTask(with: url) { (data, _, _) in //_ means we're not going to use it now let routes = try? JSONDecoder().decode([Route].self, from: data!) //decoding the data //allow us to interact with the app while API call is happening DispatchQueue.main.async { if routes != nil { completion(routes!) // print(routes!) } else { //TODO: Update error message print("we're trying to get route data - errorstate \(self.dataError), alert state \(self.showingAlert)") } } } .resume() } else { self.dataError = true print("No connection & data error set to \(self.dataError).") } print("Cell Data set to \(path.isExpensive)") } let routeQueue = DispatchQueue(label: "Route Monitor") routeMonitor.start(queue: routeQueue) } }
Here's the call I make for onAppear to call the function
Code Block //MARK: API call to get race data .onAppear{ Api().getRoutes{ (routes) in self.routes = routes print("Obserbed object: \(self.presentError.dataError)") if self.presentError.dataError == true { print("routeview error on getting data from api.getPosts \(self.presentError.dataError)") return } } }
I thought I could put an if statement after (routes) in, but I never get to that far when there is no network connecvitiy.