Mac OS下AXUIElementCopyAttributeValue解包问题求助
Hey there! Let's break down what's going wrong here and fix that error you're hitting with AXUIElementCopyAttributeValue.
What's Causing the Issue?
You've got two key problems here:
- Incorrect pointer handling: The way you're passing the
positionvariable to the API is invalid — you can't force-cast a nil optional to a mutable pointer like that. - Mismatched accessibility element: You're trying to get the
kAXPositionAttributefrom an application-level accessibility element (created viaAXUIElementCreateApplication), but this attribute only exists on individual window elements, not the app itself.
Step-by-Step Fixes
1. Fix the Pointer Passing
AXUIElementCopyAttributeValue expects a writable pointer to store the result. In Swift, you don't need to manually cast to UnsafeMutablePointer — just declare a mutable CFTypeRef? variable and pass it with the & operator, which gives the API a reference to write to.
Bad code:
var position : CFTypeRef? = nil let res : AXError = AXUIElementCopyAttributeValue(windowAccessibilityElem, kAXPositionAttribute as CFString, position as! UnsafeMutablePointer<CFTypeRef?>)
Fixed code:
var position: CFTypeRef? let res: AXError = AXUIElementCopyAttributeValue(windowAccessibilityElem, kAXPositionAttribute as CFString, &position)
2. Target the Correct Accessibility Element
Since kAXPositionAttribute belongs to window elements, you first need to fetch the list of windows from the application element, then query each window's position.
Here's the full corrected code snippet:
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) // Create accessibility element for the application let appAccessibilityElem: AXUIElement = AXUIElementCreateApplication(pid) // First, get the list of windows from the app var windows: CFTypeRef? let getWindowsRes = AXUIElementCopyAttributeValue(appAccessibilityElem, kAXWindowsAttribute as CFString, &windows) if getWindowsRes == .success, let windowElements = windows as? [AXUIElement] { // Loop through each window element to get its position for windowElem in windowElements { var position: CFTypeRef? let positionRes = AXUIElementCopyAttributeValue(windowElem, kAXPositionAttribute as CFString, &position) if positionRes == .success, let pos = position as? CGPoint { print("Window position: \(pos)") } else { print("Failed to get position, error code: \(positionRes.rawValue)") } } } else { print("Failed to fetch windows, error code: \(getWindowsRes.rawValue)") } }
3. Critical Extra Note
Don't forget that accessibility APIs require permission! You need to:
- Open System Settings → Privacy & Security → Accessibility
- Toggle on your app in the list
Without this permission, you'll keep getting AXErrorNotAuthorized no matter how correct your code is.
内容的提问来源于stack exchange,提问作者camelCaseCowboy

