0

I want to create a generic api utility that I can implement in any model. Therefore, I am currently faced with the problem of outputting error messages from the model regardless of a view. The error messages are needed to trigger a "no internet" or "poor internet connection" notification.

In general, it would help me a lot, regardless of the current view, to generate error messages in different classes in order to then inform the user of a failed process.

Here is my Code so far:

func execute(requestBody: [String: Any], withCompletion completion: @escaping (Data?, Int) -> Void) {
    
    if !CheckApiReachability().getIsApiReachable() {
        //trigger error message here
    }
Mike Keller
  • 65
  • 1
  • 7
  • Welcome to SO - Please take the [tour](https://stackoverflow.com/tour) and read [How to Ask](https://stackoverflow.com/help/how-to-ask) to improve, edit and format your questions. SO is not a code writing service, this can be implemented in several different ways. Please provide a [Minimal Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example) of the code you are trying and we can help you work out the issues. – lorem ipsum Mar 31 '21 at 08:34
  • In general, tracking reachability isn't a recommended approach. The network can fail at any instant. Just because it was available a split second before you made the network request it doesn't mean that the request can't fail with a network problem. You should try the request and handle errors as the occur. You can use a `Notification` to "broadcast" events throughout your app and since you have tagged SwiftUI, you can use Combine to subscribe to that notification – Paulw11 Mar 31 '21 at 09:28

1 Answers1

0

I have now used the Notification Center to implement an event which triggers an alert in my content view.

Emmit/ Post the Notification:

let nc = NotificationCenter.default 

self.nc.post(name: Notification.Name("InternetConnectionErrorAppeared"), object: nil)

Receive/ Subscribe/ Listen to the emited event and trigger something:

.onReceive(nc.publisher(for: Notification.Name("InternetConnectionErrorAppeared"))) { output in
        print("-- Api call failed triggered status code event")
}
Mike Keller
  • 65
  • 1
  • 7