codelearner codelearner - 2 years ago 92
Swift Question

Single delegate with multiple controllers

I ran into a situation where I want to register 2 different UIViewControllers with one delegate, because my project is showing 2 UIViewControllers at a time. When I trigger the event, I want both the controllers to get notified, but unfortunately only either controller can receive the event not both.

Here is sample code:

@objc protocol DownloaderDelegate: class {
func complete()

class Downloader {
static let sharedInstance = Downloader()
weak var delegate: DownloaderDelegate?

private init() {


func downloadFile() {

I am then using it like this in both UIViewControllers:

override viewDidLoad() {

Downloader.sharedInstance.delegate = self

Any idea how to make both the view controllers to listen to event from single delegate?

Answer Source

In fact, I think the best solution here would be to move from the delegate pattern to the Notification Pattern (more details on Apple's documentation: ).

Another solution would be to replace your delegate by an array of DownloaderDelegate. But I truly think that the Notifications solution is the cleanest and simplest.

Here is a good article on NSNotification in Swift:

Edit: You should take care of observers removal. The simplest way to do so is to add this in each class listening for events:

deinit {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download