Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 4 - Notification Center addObserver issue

I'm crashing and getting an unrecognized selector error every time a Notification arrives and the App tries to execute its associated method. Here's my code - which is in viewDidLoad:

let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(self, selector: Selector(("sayHello")), name:NSNotification.Name(rawValue: "dataDownloadCompleted"), object: nil)

The sayHello() method is quite simple - looks like this:

func sayHello() {
    print("Hello")
}

I've verified that the Notification is posted successfully and that it arrives successfully - so that's not the issue. The crash happens when the App looks to act upon the arrival of the Notification - by executing the sayHello() method. It keeps giving me that unrecognized selector error.

Any ideas what I'm doing wrong? (By the way, this worked perfectly with Swift 3 & Xcode 8, but now with Swift 4 and Xcode 9 the syntax has changed [Xcode walked me through the necessary code fixes/updates] - but the crashes keep happening.)

like image 273
Sirab33 Avatar asked Oct 11 '17 13:10

Sirab33


People also ask

What is addObserver in Swift?

addObserver(forName:object:queue:using:) Adds an entry to the notification center to receive notifications that passed to the provided block.

What is NotificationCenter default addObserver?

default — This is the notification variable you can create it globally inside your class if you having more notifications. addObserver(self, — This is for the class where we are going to observer notification.

What is NSNotification in Swift?

An object containing information broadcast to registered observers that bridges to Notification ; use NSNotification when you need reference semantics or other Foundation-specific behavior.


1 Answers

You can improve your code with these steps:

extension Notification.Name {
    static let dataDownloadCompleted = Notification.Name(
       rawValue: "dataDownloadCompleted")
}

And use it like this:

let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(self,
                               selector: #selector(YourClass.sayHello),
                               name: .dataDownloadCompleted,
                               object: nil)

But as was already pointed out, issue is solved by changing to #selector

like image 121
Vladyslav Zavalykhatko Avatar answered Sep 22 '22 08:09

Vladyslav Zavalykhatko