Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

363
Views
Swift: cómo observar si la pantalla está bloqueada en macOS

Quiero detectar si el usuario ha bloqueado su pantalla (en macOS) usando Swift .

Basado en esta respuesta , he creado el siguiente código:

 import Cocoa import Quartz if let dict = Quartz.CGSessionCopyCurrentDictionary() as? [String : Any] { let locked = dict["CGSSessionScreenIsLocked"] print(locked as? String ?? "") }

... que parece funcionar bien si ejecuto explícitamente el código.

Pero, ¿cómo es posible observar el valor para que me notifiquen cuando el valor cambió?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Puede observar las notificaciones distribuidas. No están documentados.

 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") }
over 4 years ago · Santiago Trujillo Report

0

Con Combine (disponible en macOS 10.15+):

 import Combine var bag = Set<AnyCancellable>() let dnc = DistributedNotificationCenter.default() dnc.publisher(for: Notification.Name(rawValue: "com.apple.screenIsLocked")) .sink { _ in print("Screen Locked" } .store(in: &bag) dnc.publisher(for: Notification.Name(rawValue: "com.apple.screenIsUnlocked")) .sink { _ in print("Screen Unlocked" } .store(in: &bag)
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!