Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to cast from CFTypeRef to AXUIElement in Swift

Tags:

swift

This code produces the expected debugging output type = AXUIElement, but dumps stack and says the dynamic cast failed at the actual point of the cast:

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")
        }
    }
}

What's the right way to get this done?

like image 635
James Waldrop Avatar asked Aug 30 '14 05:08

James Waldrop


1 Answers

This code worked as of XCode 6.1 and Swift 1.1.

However, it's 3 years later now and Swift has gotten a lot better. Still, this is still a top result when you search for how to work with the Accessibility API from Swift. So I'm back to update with the current simplest way I know:

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
}
like image 59
James Waldrop Avatar answered Nov 01 '22 11:11

James Waldrop