Architecture problem: how to deal with ActivityViewControllers when request errors happen

That’s a confusing situation for me. Hopefully not for you.

While loading data for a UIViewController, I present a view on the top of my ViewController with a “loading” message. I call those views “ActivityViewController”. If the request succeeds, awesome. I can dismiss the ActivityViewController and move on. But, If something goes wrong in the middle of the request, I can’t easely dismiss is because of this error is handled from inside my request class, which has no idea about the viewController I started the request from.

That’s a mock example about my code:

func makeRequest(/*someParams*/) {
  Alamofire.request(/*anotherParams*/).responseJSON { response in
    switch(response.result) {
      case .success(let JSON):
      // Great! Move on...
      case .error(let error):
      // MUST dismiss some ActivityViewController on the screen who made the request. But I don't know who is it.
      // Question: Should show a alert saying that a error happened?
      // If not done properly, a ActivityViewController blocks the user from using the app. Everything falls apart and people die.
    }            
  }
}

I hope I was clear enough. I would appreciate some design patterns to enhance this.

Thank you!

Well, your two classes need to talk to each other, so you need to put an instance of the ActivityViewController inside your Request class. Of course, experienced programmers will shout, “Then the two classes will be tightly coupled! Sad!”. Their concern is that your Request class will only be able to talk to an ActivityViewController.

Alternatively, you can make the ActivityViewController be a delegate of your Request class. Create a protocol, then have your ActivityViewController class implement the protocol. When a class implements a protocol, an instance of the class can be assigned to a variable of the protocol type. Then define a property with the protocol type in your Request class. When your Request class errors out, use the protocol property to call a protocol method implemented by your ActivityViewController–where the protocol method dismisses the ActivityViewController. Note that with the protocol architecture your Request class can talk to any class that implements the protocol, i.e. you can assign an instance of any class that implements the protocol to the protocol property in your Request class. “Loose coupling! Glad!”

This topic was automatically closed after 166 days. New replies are no longer allowed.