Why isn't application:openFile: called when the application is already running?

时光总嘲笑我的痴心妄想 提交于 2019-12-11 02:59:43

问题


I would like to handle open events when a user double-clicks on a file that was created by my application, or drags such a file onto the dock icon.

I've therefore implemented NSApplicationDelegate's application:openFile: and application:openFiles: methods, which work as expected when the application is not running.

However, if the application is already running when the open event occurs, the application becomes focused, but the above methods are never called (breakpoints inside them are not hit) and the files do not open.

I also tried implementing application:openURLs:. This method has the same behaviour: it is not called if the application is already running when the event occurs.

Do I need to implement different functions to handle opening files when the application is already running, or is there something else I need to do/set in order for the existing functions to be called in those circumstances?


回答1:


This is not mentioned in the documentation, but according to this answer the way that application:openFile: works is that it NSApplication forwards odoc Apple Events to its delegate.

Armed with this knowledge, I was able to find the following old Carbon call in the app:

osError = AEInstallEventHandler(kCoreEventClass,
                                kAEOpenDocuments,
                                g_OpenDocumentsUPP,
                                0L,
                                false);

I'm presuming this existing event handler consumed the Apple Event before NSApplication had a chance to deal with it. However, when the app is not already running, NSApplication handles the event before the line above setting up the event handler is called, hence the different behaviour.

Removing this old code from the build caused the NSApplicationDelegate methods to be called, thus fixing the issue.




回答2:


Does the following method work?

- (void)application:(NSApplication *)application 
       openURLs:(NSArray<NSURL *> *)urls;

If your delegate implements this method, AppKit does not call the
application:openFile: or application:openFiles: methods.


来源:https://stackoverflow.com/questions/50996326/why-isnt-applicationopenfile-called-when-the-application-is-already-running

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!