此代码生成预期的调试输出类型= AXUIElement,但转储堆栈并表示动态转换在转换的实际点失败: func mainWindow() { var ptr: UnmanagedAnyObject? let kAXMainWindow: CFString! = "AXMainWindow" as NSString let appRef
func mainWindow() { var ptr: Unmanaged<AnyObject>? let kAXMainWindow: CFString! = "AXMainWindow" as NSString let appRef: AXUIElement! = AXUIElementCreateApplication(self.pid()).takeRetainedValue() let err = AXUIElementCopyAttributeValue(appRef, kAXMainWindow, &ptr) if err == AXError(kAXErrorSuccess) { let val: AnyObject? = ptr?.takeRetainedValue() if val != nil { let value: AnyObject = val! let description = CFCopyTypeIDDescription(CFGetTypeID(value)) println("type = \(description)") let element = value as AXUIElement } else { println("got nil result") } } }
完成这项工作的正确方法是什么?
此代码适用于XCode 6.1和Swift 1.1.然而,现在是3年后,Swift已经变得更好了.当您搜索如何使用Swift的Accessibility API时,这仍然是最佳结果.所以我回来用我目前最简单的方式更新:
func AXUIWindowArray(processIdentifier pid:pid_t) -> [AXUIElement] { var result = [AXUIElement]() var windowList: AnyObject? = nil // [AXUIElement] let appRef = AXUIElementCreateApplication(pid) if AXUIElementCopyAttributeValue(appRef, "AXWindows" as CFString, &windowList) == .success { result = windowList as! [AXUIElement] } return result }