Search code examples
swiftmacosswift-optionals

Unwrapping issue with AXUIElementCopyAttributeValue in Mac OS


I'm trying to copy some information regarding an accessibility window option. Unfortunately, I can't resolve an error that's caused by the AXUIElementCopyAttributeValue method, despite passing in what appears to be all the correct types as parameters.

Code:

for entry in windowList! as Array {
  let ownerName: String = entry.object(forKey: kCGWindowName) as? String ?? "N/A"

  let ownerPID: Int = entry.object(forKey: kCGWindowOwnerPID) as? Int ?? 0
  let pid = Int32(ownerPID)

  //3. Get AXUIElement using PID
  let windowAccessibilityElem : AXUIElement = AXUIElementCreateApplication(pid)
  print(windowAccessibilityElem)

  var position : CFTypeRef? = nil


  /****
  * This line throws the error
  ****/
  let res : AXError = AXUIElementCopyAttributeValue(windowAccessibilityElem, kAXPositionAttribute as CFString, position as! UnsafeMutablePointer<CFTypeRef?>)

print("res is: \(res)")
...

I'm new to Swift, yet I've read and re-read the documentation on optionals and it really isn't apparent what unexpected value is being passed in- I think it has to do with the position variable, but from what I see I should be passing in the reference correctly. Any help would be apprediated.


Solution

  • You have to assign the pointer to the variable with the in-out operator &

    var position : CFTypeRef?
    let res : AXError = AXUIElementCopyAttributeValue(windowAccessibilityElem, 
                        kAXPositionAttribute as CFString, 
                        &position)
    
    • res contains the error on failure.
    • position contains the position on success.

    In the documentation an in-out parameter is indicated by On return, ...