NSNotificationCenter addObserver in Swift
It's the same as the Objective-C API, but uses Swift's syntax.
Swift 4.2 & Swift 5:
NotificationCenter.default.addObserver(
self,
selector: #selector(self.batteryLevelChanged),
name: UIDevice.batteryLevelDidChangeNotification,
object: nil)
If your observer does not inherit from an Objective-C object, you must prefix your method with @objc
in order to use it as a selector.
@objc private func batteryLevelChanged(notification: NSNotification){
//do stuff using the userInfo property of the notification object
}
See NSNotificationCenter Class Reference, Interacting with Objective-C APIs
Swift 4 - Notification Center addObserver issue
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
How can I use NSNotificationCenter to call a method in a second class?
Try this:
[newRequest performSelector:@selector(getTheRequest:) withObject:@"mySite"];
Please note that class names should start from the capital letter and getters should not use the get prefix by Apple's coding standards Introduction to Coding Guidelines for Cocoa
NSNotificationCenter addobserver not calling the selector method in SWIFT
You sent the notification before the second view controller could add itself as observer.
If the goal is to send data to the next ViewController, I suggest using prepareForSegue
.
You mentioned that your second ViewController is embedded in a Navigation Controller
. That's ok. You can use something like this:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "YOUR_IDENTIFIER" {
// The destination ViewController is a NavigationController.
// The top ViewController of the NavigationController is your target.
// In this example we are just setting a String in the destination ViewController.
if let navigationController = segue.destinationViewController as? UINavigationController {
if let myTargetViewController = navigationController.topViewController as? MyTargetViewController {
myTargetViewController.myStringVar = "My string value."
}
}
}
}
You can also be fancy and write the same thing like this:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let navigationController = segue.destinationViewController as? UINavigationController,
myTargetViewController = navigationController.topViewController as? MyTargetViewController
where segue.identifier == "YOUR_IDENTIFIER" {
myTargetViewController.myStringVar = "My string value."
}
}
As explained here.
Cheers!
when to call removeObserver for nsnotificationcenter
A couple of observations:
I infer from your code comment that you are contemplating removing the observer inside the selector for that particular notification. That is a fine practice.
I'd be wary about just calling
removeObserver
, though, because that will remove all observers that you may have set up. If you are calling this inside the routine that is the selector for a particular notification, then I might be inclined to remove only that particular notification:NSNotificationCenter.defaultCenter().removeObserver(self, name: NotificationConstants.pvpConnEstablishedString, object: nil)
Yes, at this point, you may only be observing a single notification, so this may feel unnecessary, but if at some future date you add completely separate notification handling code for a different notification, you want to make sure that you don't accidentally remove all observers when handling a particular notification.
You might want to be sensitive to the possibility that this view controller may be dismissed before the notification comes in. In that case, it might be prudent to also add
removeObserver
in thedeinit
method for the view controller.In this case, the simple
removeObserver(self)
is prudent (because it's reasonable to remove all observers when the view controller is deallocated).
Related Topics
Xcode 6 & Swift: Black Bars Appear Above and Below the Viewcontroller on iOS 7 iPhone 5 Device
Peek/Pop Preview Ignores Cell Corner Radius in Collection View
Drawing an Infinite Grid in iOS
Saving Already Created Live Photos
Swift Continuous Rotation Animation Not So Continuous
How Parsing Firebase Fdatasnapshot JSON Data in Swift
How to Fill a Circle Color by Percentage Value
Include Pods in Main Target and Not in Watchkit Extension
My Uiviews Muck-Up When I Combine Uipangesturerecognizer and Autolayout
Use More Than One Firebase Database in Single App - Swift
How to Retrieve Image Stored in Firebase to Show It in View Image View
How Do Ruler Apps Stay Accurate on All Devices
Shift Avplayer Captions When Subview Overlaps Them
Nsubiquityidentitydidchangenotification and Sigkill
Uitextfield Keyboard with Only Alphabet, No Numbers, No Caps, No Spacebar
How to Store JSON Decodable Values into Coredata Using Swift