Not getting screenLock notification on Swift 4 on mac - swift

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
}

Related

orientationDidChangeNotification has been renamed to 'NSNotification.Name.UIDeviceOrientationDidChange'

i am updated to flutter 2.10 and get this issue in ios MLKit in the class
OrientationHandler
in this section of the handler code
NotificationCenter.default.addObserver(forName: UIDevice.orientationDidChangeNotification, object: nil, queue: nil, using: orientationDidChange(_:))
i get this error :
'orientationDidChangeNotification' has been renamed to 'NSNotification.Name.UIDeviceOrientationDidChange'
this class written like
class OrientationHandler {
var lastKnownOrientation: UIDeviceOrientation!
init() {
setLastOrientation(UIDevice.current.orientation, defaultOrientation: .portrait)
UIDevice.current.beginGeneratingDeviceOrientationNotifications()
NotificationCenter.default.addObserver(forName: UIDevice.orientationDidChangeNotification, object: nil, queue: nil, using: orientationDidChange(_:))
}
func setLastOrientation(_ deviceOrientation: UIDeviceOrientation, defaultOrientation: UIDeviceOrientation?) {
// set last device orientation but only if it is recognized
switch deviceOrientation {
case .unknown, .faceUp, .faceDown:
lastKnownOrientation = defaultOrientation ?? lastKnownOrientation
break
default:
lastKnownOrientation = deviceOrientation
}
}
func orientationDidChange(_ notification: Notification) {
let deviceOrientation = UIDevice.current.orientation
setLastOrientation(deviceOrientation, defaultOrientation: nil)
}
deinit {
UIDevice.current.endGeneratingDeviceOrientationNotifications()
}
}
how to solve this error
after searching , i solve it like this
NotificationCenter.default.addObserver(forName: NSNotification.Name.UIDeviceOrientationDidChange, object: nil, queue: nil, using: orientationDidChange(_:))

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 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) {
}

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)

How is that possible to post notification after 1 second delay or in a dispatch asyn?

i just want to call a method after loading my view. i have set notification to one view and postnotification to other view you will get more idea from my code.. here is my code..
in a one.swift file
override func viewDidLoad() {
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "InsertNote:", name: "insert", object: nil)
}
func InsertNote(notification:NSNotification)
{
println("blablalbla")
}
in a second.swift file
override func viewDidLoad() {
super.viewDidLoad()
var timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("getData"), userInfo: nil, repeats: false)
}
func getData()
{
NSNotificationCenter.defaultCenter().postNotificationName("insert", object: nil)
}
i have try also in a dispatch_asynch but still it is not work.
Try this
let delayInSeconds: Double = 1
override func viewDidLoad() {
super.viewDidLoad()
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC))), dispatch_get_main_queue()){
NSNotificationCenter.defaultCenter().postNotificationName("insert", object: nil)
}
}
The only reason I can come up with that this doesn't work, is that your first ViewController A is already deallocated when you send the notification with the second ViewController B. So, you are sending the notification with B correctly, but A isn't around to receive it.
You can test this by adding an observer in B as well.
override func viewDidLoad() {
super.viewDidLoad()
var timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("getData"), userInfo: nil, repeats: false)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "insertNote:", name: "insert", object: nil)
}
func getData() {
NSNotificationCenter.defaultCenter().postNotificationName("insert", object: nil)
}
func insertNote:(note: NSNotification) {
print("Banana")
}
// Should print 'Banana' after one second.