Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

removeObserver for Notification Swift3

Tags:

ios

swift

I have a strange issue. I register and unregister my Notification like so:

func doRegisterNotificationListener() {
        NotificationCenter.default.addObserver(forName: Notification.Name(rawValue: "RateAlertRated"), object: nil, queue: nil, using: rateDidRate)
    }

    func doUnregisterNotificationListener() {
        NotificationCenter.default.removeObserver(self, name: Notification.Name(rawValue: "RateAlertRated"), object: nil)
    }

    func rateDidRate(notification: Notification) {
        let rating = notification.userInfo?["score"] as? Int
        let message = notification.userInfo?["message"] as? String
        let response = Response(rating: rating, message: message)
        output.presentRated(response)
    }

This view controller is in a UITabBarController. doRegisterNotificationListener is called in viewDidAppear and doUnregisterNotificationListener is called in viewDidDisappear. When I switch between tabs the register and unregister methods are being called correctly (I tested using a print statement). However if I fire a notification it will still be received even though doUnregisterNotificationListener was called last. Any ideas what I might be doing wrong here?

Quick note:

Also tried:

NotificationCenter.default.removeObserver(self)

This also doesn't work.

like image 366
KexAri Avatar asked Oct 30 '22 10:10

KexAri


1 Answers

I have tested your code and once i register observer with this type it is not called when you doUnregister it. please try this.

NotificationCenter.default.addObserver(self, selector: #selector(rateDidRate(notification:)), name: Notification.Name(rawValue: "RateAlertRated"), object: nil)
like image 117
Pankaj K. Avatar answered Nov 15 '22 07:11

Pankaj K.