简体   繁体   中英

NSNotification handling in multiple UIViewContoller in Swift

I have few UIViewController's subclass. Each and every class has network calls, all these network calls are handled in separate class, whenever I get failure as response instead of delivery failure response to each class I want to show an alert by posting notification from my network class. All my alerts are displayed view an extension to UIViewController . Is there a way to add observer for the notification in my extension, so that I can post notification from my network class and the alert is show using this UIViewController's extension instead of adding/removing observer in each of my UIViewController .

  1. If your intention is to just show an error alert then I would recommend adding AppDelegate as notification listener and then present an alert on notification fire.
  2. I, personally, would recommend completion blocks for networking making code scalable and debugging easy.
  3. There is another alternative of creating a UIViewController subclass (say CustomVC) and registering it for the notification with an empty handler. And then create all your view controllers subclass of CustomVC. Each of your view controllers would however have to implement the handler and execute code based on the specific VC.

If you only want to show alert, you can do it by displaying it from your network class instead of notification.

If you have some specific functionality to implement for every UIViewController in case of failure then create a parent controller (subclass of UIViewController) and inherit all of your UIViewController from parent class and implement all the notification work in parent controller even if you want any funcionality specific to a controller, you can override the parent class method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM