index.uts 1.2 KB
Newer Older
1
import { NotificationCenter } from 'Foundation';
2 3 4 5 6 7
import { UIApplication } from "UIKit"

/**
 * 定义监听截屏事件工具类
 */
class CaptureScreenTool {
8
	static listener: UTSCallback | null;
9 10
	
	// 监听截屏
11
	static listenCaptureScreen(callback: UTSCallback | null) {
12 13 14 15 16 17 18 19 20 21 22 23
		this.listener = callback
		
		// 注册监听截屏事件及回调方法
		// target-action 回调方法需要通过 Selector("方法名") 构建
		const method = Selector("userDidTakeScreenshot")
		NotificationCenter.default.addObserver(this, selector = method, name = UIApplication.userDidTakeScreenshotNotification, object = null)
	}
	
	// 捕获截屏回调的方法
	// target-action 的方法前需要添加 @objc 前缀
	@objc static userDidTakeScreenshot() {
		// 回调
24
		this.listener?.({})
25 26 27
	}
	
	// 移除监听事件
28
	static removeListen(callback: UTSCallback | null) {
29 30
		this.listener = null
		NotificationCenter.default.removeObserver(this)
31
		callback?.({})
32 33 34 35 36 37
	}
}

/**
 * 开启截图监听
 */
38
export function onUserCaptureScreen(callback: UTSCallback | null) {
39 40 41 42 43 44
	CaptureScreenTool.listenCaptureScreen(callback)
}

/**
 * 关闭截屏监听
 */
45
export function offUserCaptureScreen(callback: UTSCallback | null) {
46
	CaptureScreenTool.removeListen(callback)
47
}