-[NSWorkspace openFile:withApplication:] wait for opening Application

3.8k views Asked by At

In my Obj-C App I'm using the following code to open a file in Pages (or any other Application):

[[NSWorkspace sharedWorkspace] openFile:theUrl withApplication:@"Pages"];

Mainly when bigger files are opened, this may take a few seconds to finish. So I want my Application to wait for Pages until it completely opened the file.

The following code is how I would love to do it:

[[NSWorkspace sharedWorkspace] openFile:theUrl withApplication:@"Pages" onFinish:@selector(pagesfinishedopening)];

Of course I could simply use the sleep() function, but this would slow down the app on small files and would not work when the files are bigger than excepted.

I already tried something with the NSApplication, but then the opening of the file in Pages is not respected, only the start of the target application can be monitored.

Any Ideas?

2

There are 2 answers

1
dafi On

You can listen for notifications arriving from NSWorkSpace like shown below

- (void)myMethod {
    [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self
                                                       selector:@selector(appDidLaunch:)
                                                           name:NSWorkspaceDidLaunchApplicationNotification
                                                         object:nil];

    [[NSWorkspace sharedWorkspace] openFile:theUrl withApplication:@"Pages"];    
}

- (void)appDidLaunch:(NSNotification*)notification {
    NSLog(@"app info: %@", [notification userInfo]);
}
0
user1938752 On

Perhaps you could use scriptingbridge to check whether pages opened the file, and then continue on with whatever your app needs to do once pages opens the file. Any app that supports apple script can be scripted using scriptingbridge. Its a bit difficult to find documentation for apps, but I think it should be similar to apple script.

Soem ScriptingBridge documentation:

http://www.mugginsoft.com/AutomationDocs

Apple ScriptingBridge usage guide:

https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ScriptingBridgeConcepts/UsingScriptingBridge/UsingScriptingBridge.html

The above explains how to use scripting bridge, and has an example for Pages (very brief). With some experimentation you should be able to have your app check whether pages opened the file every second until its open (i.e. while file is not open, wait one second - probably not the best way to do it, but its something). I think there are undocumented notifications as well. Hope it helps somewhat.