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

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

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

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