Not Getting Screenlock Notification on Swift 4 on Mac

Swift: How to observe if screen is locked in macOS

You can observe distributed notifications. They are not documented.

let dnc = DistributedNotificationCenter.default()

lockObserver = dnc.addObserver(forName: .init("com.apple.screenIsLocked"),
object: nil, queue: .main) { _ in
NSLog("Screen Locked")
}

unlockObserver = dnc.addObserver(forName: .init("com.apple.screenIsUnlocked"),
object: nil, queue: .main) { _ in
NSLog("Screen Unlocked")
}

How to lock/unlock screen in mac programatically

Using an authorization plugin is quite involved, but possible. I would recommend simply launching the screensaver. If the screen saver is set to lock when launched, this will fulfill your requirement of forcing the lock

Note that the screen saver is just an application located at this path:-

/System/Library/Frameworks/ScreenSaver.framework/Versions/A/Resources/ScreenSaverEngine.app

To launch every 45 minutes, follow Apple's guide to Scheduling Timed Jobs with launchd.

If you really want to have it unlocked after a period of time, then you'll have to research the Authorization Plugin; the API can be found here.

How to prevent screen lock on my application with swift on iOS

Use this:

Objective-C:

[[UIApplication sharedApplication] setIdleTimerDisabled: YES];

Swift (legacy):

UIApplication.sharedApplication().idleTimerDisabled = true

Swift 3 and above:

UIApplication.shared.isIdleTimerDisabled = true

Make sure to import UIKit.

Here is the link to the documentation from developer.apple.com.

Force lock screen

If you want to know how they do this :

The phone is paired with the bluetooth device included in their hardware.
If you check further, you will notice that this Bluetooth device has the "Keyboard" profile: just check on your phone, you will see it is recognized as a wireless keyboard... Interesting... Do you see the answer coming ? ...

You Bet ! The device sends to the phone the lock screen command-key as if it was a connected bluetooth keyboard (yes, because a BT Keyboard can actually do this). And here you go.

=== EDIT ===

Please take a look at this HID usage table, you will find some useful command codes. The key codes we're looking for are most probably 0x81 or 0x82.



Related Topics



Leave a reply



Submit