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 successfullyHowever
children is nilreturnVal 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.
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:

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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With