You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在macOS应用AppDelegate中阻止录屏?求iOS对应API替代方案

在macOS AppDelegate中实现屏幕录制检测与禁用(替代iOS API)

背景

你在iOS中通过UIScreen.main.isCaptured和UIScreen.capturedDidChangeNotification实现的屏幕录制检测与禁用功能,在macOS中可以通过对应的NSScreen API或CoreGraphics接口替代,以下是完整的实现方案:

等效代码实现

import Cocoa
import FlutterMacOS
import CoreGraphics // 若使用CGDisplayIsCaptured则需导入

@NSApplicationMain
class AppDelegate: FlutterAppDelegate {

    override func applicationDidFinishLaunching(_ aNotification: Notification) {
        // 监听屏幕录制状态变更通知
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(preventScreenRecording),
            name: NSScreen.capturedDidChangeNotification,
            object: nil
        )
        
        // 应用启动时初始化检查状态
        checkScreenCaptureState()
        
        GeneratedPluginRegistrant.register(with: self)
        super.applicationDidFinishLaunching(aNotification)
    }
    
    @objc private func preventScreenRecording() {
        checkScreenCaptureState()
    }
    
    private func checkScreenCaptureState() {
        // 方案1:使用NSScreen的isCaptured(macOS 10.15+)
        let isCaptured = NSScreen.main?.isCaptured ?? false
        
        // 方案2:若isCaptured被废弃,改用CoreGraphics接口
        // let isCaptured = CGDisplayIsCaptured(CGMainDisplayID())
        
        print("isCaptured: \(isCaptured)")
        if isCaptured {
            blurScreen()
        } else {
            removeBlurScreen()
        }
    }
    
    // 实现屏幕模糊(禁用录制可视化效果)
    private func blurScreen() {
        guard let window = NSApp.mainWindow, let contentView = window.contentView else { return }
        // 避免重复添加模糊层
        contentView.subviews.filter { $0 is NSVisualEffectView }.forEach { $0.removeFromSuperview() }
        
        let blurView = NSVisualEffectView(frame: contentView.bounds)
        blurView.autoresizingMask = [.width, .height]
        blurView.blendingMode = .behindWindow
        blurView.material = .dark // 可根据需求调整模糊材质
        contentView.addSubview(blurView)
    }
    
    // 移除屏幕模糊
    private func removeBlurScreen() {
        guard let contentView = NSApp.mainWindow?.contentView else { return }
        contentView.subviews.filter { $0 is NSVisualEffectView }.forEach { $0.removeFromSuperview() }
    }
}

关键API说明

  • 状态变更通知:用NSScreen.capturedDidChangeNotification替代iOS的UIScreen.capturedDidChangeNotification,同样通过NotificationCenter监听屏幕录制状态的变化。
  • 录制状态检测:
    • 优先使用NSScreen.main?.isCaptured(macOS 10.15+支持),接口逻辑和iOS一致。
    • 若该接口被标记为废弃,可改用CoreGraphics的CGDisplayIsCaptured(CGMainDisplayID()),直接检测主屏幕是否被录制。
  • 屏幕模糊实现:macOS中使用NSVisualEffectView实现模糊效果,替代iOS的模糊方案,注意设置自动布局掩码以适配窗口大小变化。

内容的提问来源于stack exchange,提问作者Mohammad Davarpanah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 21:57:43