在開(kāi)發(fā)過(guò)程可能會(huì)遇到要監(jiān)控當(dāng)前app的一些工作情況潮饱,如彈出窗口,移動(dòng)窗口位置等犯戏。查詢資料后固蚤,發(fā)現(xiàn)可以通過(guò)利用AXObserver監(jiān)控app的一些變化。具體步驟如下:
1 聲明觀察者
var observer: AXObserver? = nil
2 利用BundleIdentifier獲取要監(jiān)控的app
let apps = NSRunningApplication.runningApplications(withBundleIdentifier: "com.iqiyi.player")
let app = apps.last
let pid: pid_t = (app?.processIdentifier)!
3 創(chuàng)建回調(diào)閉包歹茶,這里只是打印通知
let myCallBack: AXObserverCallback = {
(observer: AXObserver, app: AXUIElement, noti: CFString, refcon: UnsafeMutableRawPointer?) -> Swift.Void in
print(noti)
}
4 創(chuàng)建觀察者
AXObserverCreate(pid, myCallBack, &observer)
5 將AXObserver加入Runloop中
CFRunLoopAddSource(CFRunLoopGetCurrent(), AXObserverGetRunLoopSource(observer!), CFRunLoopMode.defaultMode)
6 添加需接收到通知
AXObserverAddNotification(observer!, AXUIElementCreateApplication(pid), kAXWindowMovedNotification as CFString, nil)