I found a reliable way to ask Automation permission in my app.
Run a command to send System Event in shell use osascript, like this:
osascript -e 'tell application "System Events" to keystroke "a"'
If this is the first time you have sent System Event on user's computer, an authorization dialog will pop up by system.
If you want to check the Automation permission status, you can run the same script via NSAppleScript.
NSAppleScript *aScript = [[NSAppleScript alloc] initWithSource:source];
NSDictionary<NSString *, id> *errorInfo;
[aScript executeAndReturnError:&errorInfo];
This code will silently fail in both cases when the first time sending System Event and when the authorization had denied. And the error code here will be -1743.
It should be noted that if the Accessibility permission is unauthorized, the error code here will be 1002. So first make sure that accessibility permissions are authorized.