Search code examples
macosswiftcocoawebviewwebkit

Unexpected exceptions raised while registering handler for WebHistory Notifications, what's the wrong?


In a swift OS X project, I'm trying to register an observer to handle WebHistory Notifications sent from a WebView. I think that the registration process is successful, but when my notification handler should be invoked an uncaught exception is raised; specifically, the error message is "-[project_name.HistoryController didAddHistoryItems]: unrecognized selector sent to instance 0x600000002420". But HistoryController defines the method

func didAddHistoryItems(notification: NSNotification).

So, what's wrong? I am really struggling. I've been fighting against this issue for days now. I've tried instantiating my HistoryController in various places in the program (applicationDidFinishLaunching, viewDidLoad method of my WebView, viewDidAppear method of my WebView) and even instantiating it as a global variable, but the result does not change. The observer is registered as follows:

NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("didAddHistoryItems"), name: WebHistoryItemsAddedNotification, object:nil)

Can anyone help? What am I missing?


Solution

  • You need to add the : to the end of the selector to indicate that the method has a parameter. The line should be:

    NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("didAddHistoryItems:"), name: WebHistoryItemsAddedNotification, object:nil)

    You also don't need the Selector(...) part and can simply do:

    NSNotificationCenter.defaultCenter().addObserver(self, selector: "didAddHistoryItems:", name: WebHistoryItemsAddedNotification, object:nil)