在 MacOS/React Native 中捕获活动应用程序通知

问题描述 投票:0回答:1

我正在使用 React Native 构建 MacOS 应用程序。我想找出用户何时切换应用程序并在发生时抓取屏幕截图。我有以下玩具实现:

import Foundation
import AppKit

@objc(ScreenShotModule)
public class ScreenShotModule: NSObject, RCTBridgeModule {
  
  public static func moduleName() -> String! {
    return "ScreenShotModule"
  }
  
  var count:Int = 0
  
  override init() {
    super.init()
    print("called init")
    NotificationCenter.default.addObserver(
      self,
      selector: #selector(appDidBecomeActive),
      name: NSWorkspace.didActivateApplicationNotification,
      object: nil)
  }
  
  @objc func appDidBecomeActive(notification: NSNotification) {
    print("got notified")
    let displayId = CGMainDisplayID()
    guard let image = CGDisplayCreateImage(displayId) else { return }
        
    let bitmapRep = NSBitmapImageRep(cgImage: image)
    guard let imageData = bitmapRep.representation(using: .png, properties: [:]) else { return }
        
    let fileManager = FileManager.default
    let directoryURLs = fileManager.urls(for: .picturesDirectory, in: .userDomainMask)
        
    if let documentDirectory = directoryURLs.first {
      let filePath = documentDirectory.appendingPathComponent("screenshot_\(count).png")
      do {
        try imageData.write(to: filePath)
        count += 1
        print("Screenshot saved to: \(filePath)")
      } catch {
        print("Error saving screenshot: \(error)")
      }
    }
  }
  
  @objc func triggerAppDidBecomeActive() {
      let dummyNotification = NSNotification(name: NSNotification.Name(""), object: nil)
      self.appDidBecomeActive(notification: dummyNotification)
  }
  
  @objc func postNotification() {
    print("posted!")
    NotificationCenter.default.post(name: NSWorkspace.didActivateApplicationNotification, object: "foo",
                                    userInfo: ["key": "Value"])
  }
  
  @objc public static func requiresMainQueueSetup() -> Bool {
    return true
  }
}

这是有效的,因为我可以通过

triggerAppDidBecomeActive
手动截图,并且我可以通过
postNotification
发布虚假事件时截图。但是,当我运行应用程序并在应用程序之间切换时,没有截取屏幕截图。因此,不知何故,我的切换应用程序不会发送事件,或者不会触发:

NotificationCenter.default.addObserver(
      self,
      selector: #selector(appDidBecomeActive),
      name: NSWorkspace.didActivateApplicationNotification,
      object: nil)

我已打开和关闭应用程序沙箱,没有进行任何更改。我也尝试过使用 DistributedNotificationCenter,但这也不起作用。如何判断用户何时切换活动应用程序?

swift macos notifications
1个回答
0
投票

您正在使用

NotificationCenter.default.addObserver
,但您应该使用
NSWorkspace.shared.addObserver

我相信这对于

NSWorkspace.*
通知来说是普遍正确的。

© www.soinside.com 2019 - 2024. All rights reserved.