Swift Notification is sent but not received - swift

I added an observer to be notified when a charger is connected.
CFNotificationCenterAddObserver(
CFNotificationCenterGetDarwinNotifyCenter(),
nil,
{ (_, _, _, _, _) in
print("Sending...")
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "test123"), object: nil)
},
kIOPSNotifyAttach as CFString?,
nil,
.deliverImmediately
)
When the charger is connected the a notification is sent so that I can react in my application.
So I added an observer in my app
NotificationCenter.default.addObserver(
self,
selector: #selector(reactToNotification(_:)),
name: NSNotification.Name(rawValue: "test123"),
object: nil)
The notification is sent correctly but the associated function is never called.
#objc func reactToNotification(_ notification: Notification) {
print("Receiving...")
}
Is there a specific problem in my concept?

It's really mismatch issue
You sent this notification NSNotification.Name(rawValue: "test123")
But expected to get this: NSNotification.Name(rawValue: "test")
It's just naming issue!

Related

Add observer without using selector

I need to add observes in my project, but since the manager that I work with, doesn't let me to use #objc in the functions, is there anyway that I can use this function without using #objc?
func createObservers() {
NotificationCenter.default.addObserver(self, selector: #selector(self.updatedata(notification:)),
name: Notification.Name(rawValue: updateNotificationKey), object: nil)
}
#objc dynamic func updatedata(notification: NSNotification) {
updateDataIcon()
}
Your help will be appreciated.
You can use this with the inline block
NotificationCenter.default.addObserver(forName: Notification.Name(rawValue: updateNotificationKey) , object: nil, queue: .main) { [weak self] notification in
// to do
}

How to control/override notifications being sent by NSTableView/NSOutlineView

I am wondering how I can override the notification being sent when the selection within a NSOutlineView | NSTableView has been changed. What I need to achieve is to add userInfo data to the notification being sent out.
I know that outlineViewSelectionDidChange of a NSOutlineView can be used to send out a custom notification like this:
func outlineViewSelectionDidChange(_ notification: Notification) {
NotificationCenter.default.post(name: NSOutlineView.selectionDidChangeNotification, object: self, userInfo: ["test": 1])
}
However, when I connect an observer to this notification ...
NotificationCenter.default.addObserver(
self,
selector: #selector(onSelectSetViewController(_:)),
name: NSOutlineView.selectionDidChangeNotification,
object: nil
)
... , I receive this as an output:
#objc
private func onSelectSetViewController(_ notification: Notification) {
print(notification)
}
name = NSOutlineViewSelectionDidChangeNotification, object = Optional(), userInfo = Optional([AnyHashable("test"): 1])
name = NSOutlineViewSelectionDidChangeNotification, object = Optional(), userInfo = nil
So the notification is being sent twice. How can I avoid this and sent out a notification with userInfo data only once?
Just change the name of your forwarding notification to something else and your notification will be sent only once. Then add an observer to listen to the forwarding notification. That will solve your problem:
func outlineViewSelectionDidChange(_ notification: Notification) {
NotificationCenter.default.post(name: MySelectionDidChangeNotification, object: self, userInfo: ["test": 1])
}
Then add this observer:
NotificationCenter.default.addObserver(
self,
selector: #selector(onSelectSetViewController(_:)),
name: MySelectionDidChangeNotification,
object: nil
)

How to detect day change in Swift

I want my app to act when there is a change to another day.
So, in my appDelegate, I put
func applicationSignificantTimeChange(_ application: UIApplication){
//this one fires
}
and in the ViewController that should update its content I do:
override func viewDidLoad() {
NotificationCenter.default.addObserver(self, selector: #selector(self.dayChanged(notification:)), name: Notification.Name("significantTimeChangeNotification"), object: nil)
}
and
#objc func dayChanged(notification: NSNotification){
//this one doesn't fire
}
somehow, while the func in AppDelegate is called, the observer seems to be blind for that event.
Is this syntax, or just plain misunderstanding of the mechanism?
You need to add an observer for "UIApplicationSignificantTimeChangeNotification":
NotificationCenter.default.addObserver(self, selector: #selector(dayChanged), name: UIApplicationSignificantTimeChangeNotification, object: nil)
For Swift 4.2 or later
NotificationCenter.default.addObserver(self, selector: #selector(dayChanged), name: UIApplication.significantTimeChangeNotification, object: nil)
Note: If your intent is to be notified when the day changes you can use .NSCalendarDayChanged ("NSCalendarDayChangedNotification") instead of UIApplication.significantTimeChangeNotification.
NotificationCenter.default.addObserver(self, selector: #selector(dayChanged), name: .NSCalendarDayChanged, object: nil)
And add the selector method to the view controller where you would like to monitor the day changes:
#objc func dayChanged(_ notification: Notification) {
}

Not getting screenLock notification on Swift 4 on mac

For some reason I'm not getting the ScreenIsLocked and ScreenIsUnlocked notifications. I defined that the screen get locked 0 seconds after the screen saver starts and yet no log:
import Cocoa
#NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
#objc func screenLocked() {
NSLog("yes")
}
func applicationDidFinishLaunching(_ aNotification: Notification) {
// Insert code here to initialize your application
NotificationCenter.default.addObserver(
self,
selector: #selector(AppDelegate.screenLocked),
name: Notification.Name("com.apple.screenIsLocked"),
object: nil)
NotificationCenter.default.addObserver(
self,
selector: #selector(AppDelegate.screenLocked),
name: Notification.Name("com.apple.screenIsUnlocked"),
object: nil)
NotificationCenter.default.addObserver(
self,
selector: #selector(AppDelegate.screenLocked),
name: Notification.Name("com.apple.screensaver.didstart"),
object: nil)
NotificationCenter.default.addObserver(
self,
selector: #selector(AppDelegate.screenLocked),
name: Notification.Name("com.apple.screensaver.didstop"),
object: nil)
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
}
}
Use NSDistributedNotificationCenter
This is from a post by Kane Cheshire:
https://kanecheshire.com/blog/2014/10/13/351/
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
NSDistributedNotificationCenter *center = [NSDistributedNotificationCenter defaultCenter];
[center addObserver:self
selector:#selector(screenLocked)
name:#"com.apple.screenIsLocked"
object:nil];
[center addObserver:self
selector:#selector(screenUnlocked)
name:#"com.apple.screenIsUnlocked"
object:nil];
}
In Swift:
DistributedNotificationCenter.default().addObserver(self,
selector: #selector(screenLocked),
name: "com.apple.screenIsLocked",
object: nil)
DistributedNotificationCenter.default().addObserver(self,
selector: #selector(screenLocked),
name: "com.apple.screenIsUnlocked",
object: nil)
It's slightly different syntax now for the notification names.
DistributedNotificationCenter.default().addObserver(forName: NSNotification.Name(rawValue: "com.apple.screenIsLocked"),
object: nil,
queue: .main) { [weak self] _ in
// Handle it
}
DistributedNotificationCenter.default().addObserver(forName: NSNotification.Name(rawValue: "com.apple.screenIsUnlocked"),
object: nil,
queue: .main) { [weak self] _ in
// Handle it
}

NsNotificationCenter is not working

Actually i'm new in swift i got stuck here,Anyone can solve this Problem. actOnSpecialNotification Func is not calling on fireNotification in ViewController.swift
In ViewController.swift
func fireNotification() -> Void {
NotificationCenter.default.addObserver(self, selector:
#selector(vikas.updateNotificationSentLabel), name:
NSNotification.Name(rawValue: mySpecialNotificationKey), object: nil)
}
func updateNotificationSentLabel() {
print("sent")
}
in SecondVC.swift
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector:
#selector(ViewController.actOnSpecialNotification), name:
NSNotification.Name(rawValue: mySpecialNotificationKey), object: nil)
}
func actOnSpecialNotification() {
print("listen")
}
First of all add Observer to your FirstViewConroller.
FirstViewConroller
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(YourClassName.methodOfReceivedNotification(_:)), name:”test”, object: nil)
Now, add the relevant selector method in same ViewController which will be called once the notification will be fired.
func methodOfReceivedNotification(notification: Notification){
//Take Action on Notification
}
Now, you can fire the notification using below lines which will call the above method which resides in FirstViewController
SecondViewController
NSNotificationCenter.defaultCenter().postNotificationName(“test”, object: nil)