Vincent Pfenninger
Vincent Pfenninger

Reputation: 59

Activate Application on Screen Unlock

I'm writing an application for macOS and I want it to detect when the screen is unlocked and then make itself become the active application. I'm trying to use "com.apple.screenIsUnlocked", but it doesn't seem to work (the function doesn't even run). I also tried using NSWorkspaceDidWakeNotification where I got the function to run but the app didn't actually activate (presumably because the screen was still locked). Here is what I currently have (I'm using Xcode 9.2 and Swift 4):

import Cocoa

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
    @IBOutlet weak var window: NSWindow!


    func applicationDidFinishLaunching(_ aNotification: Notification) {
        // Insert code here to initialize your application
        NSWorkspace.shared.notificationCenter.addObserver(self, selector: #selector(AppDelegate.screenDidUnlock), name:  NSNotification.Name(rawValue: "com.apple.screenIsUnlocked"), object: nil)
    }

    func applicationWillTerminate(_ aNotification: Notification) {
        // Insert code here to tear down your application
    }

    @objc func screenDidUnlock() {
        NSApplication.shared.activate(ignoringOtherApps: true)
        print("Did Run")
    }

Upvotes: 1

Views: 721

Answers (2)

Doug
Doug

Reputation: 3190

The com.apple.screenIsUnlocked notification is posted to the DistributedNotificationCenter rather than the NSWorkspace's notificationCenter, so the observer should be added like this:

DistributedNotificationCenter.default().addObserver(self, selector: #selector(AppDelegate.screenDidUnlock), name: NSNotification.Name(rawValue: "com.apple.screenIsUnlocked"), object: nil)enter code here

Upvotes: 2

saj
saj

Reputation: 142

I don't think apple allows you to run any application in the background.

Upvotes: -2

Related Questions