Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift4: `AXUIElementCopyAttributeValue()` returns `AXError.cannotComplete`

On running the following code:

let pid = getAppPid()
let AXApp = AXUIElementCreateApplication(pid)

var children: CFTypeRef?
let returnVal = AXUIElementCopyAttributeValue(AXApp,
    kAXChildrenAttribute as CFString, &children)
  • AXApp gets created successfully

However

  • children is nil
  • returnVal is AXError.cannotComplete ("A fundamental error has occurred, such as a failure to allocate memory during processing.")

I've seen code on stack overflow and elsewhere using exactly the same method as I am.

What am I missing.

I am using Xcode 9/Swift 4 on MacOS High Sierra.

EDIT:

I should add that Xcode has accessibility permissions, and I am able to successfully do other stuff that requires accessibility permission like CGEvent.tapCreate() to monitor global keyboard events etc.

like image 577
Anshuman Sharma Avatar asked Aug 15 '26 13:08

Anshuman Sharma


1 Answers

To fix this error you should turn off App Sandbox by doing the following:

You can turn off Sandboxing by removing it from the Signing & Capabilities tab:

enter image description here

After that AXError.cannotComplete should not appear again. If you still get some issues you can try to get the selected text of the frontmost app like this:

import ApplicationServices
import Cocoa

func getSelectedText() -> String? {
    let systemWideElement = AXUIElementCreateSystemWide()

    var selectedTextValue: AnyObject?
    let errorCode = AXUIElementCopyAttributeValue(systemWideElement, kAXFocusedUIElementAttribute as CFString, &selectedTextValue)
    
    if errorCode == .success {
        let selectedTextElement = selectedTextValue as! AXUIElement
        var selectedText: AnyObject?
        let textErrorCode = AXUIElementCopyAttributeValue(selectedTextElement, kAXSelectedTextAttribute as CFString, &selectedText)
        
        if textErrorCode == .success, let selectedTextString = selectedText as? String {
            return selectedTextString
        } else {
            return nil
        }
    } else {
        print(errorCode.rawValue)
        return nil
    }
}
like image 160
SwiftNewling Avatar answered Aug 18 '26 02:08

SwiftNewling



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!