NSApplicationDelegate application:openFile. Never reaches to openFile: function

3.2k views Asked by At

I want to open a file dropping it on the app icon. When I do it my app is opened so the file extension is well defined and related to my app. But the application:openFile: function never is called. so I can't open the file dropped in my app. I traced openFile: but never goes.

All the answers that I found are just to add in the delegate the openFile: and that's all but not in my case.

Any help will be very appreciate it. Thanks a lot in advance.

This is my environment.

The plist has got the extension of files to be opened. My app is opened when I drop the files.

I initialize my delegate at the beggining of the app,

   mydelegate = [[MyController alloc] init];

And in the delegate,

in the include,

@interface MyController : NSObject <NSApplicationDelegate> {

@private

     NSWindow *window;
}

@property (assign) IBOutlet NSWindow *window;

-(id)   init;

-(BOOL) application: (NSApplication*)sharedApplication openFile:(NSString*) fileName;

@end

And in the .m file,

@implementation MyController

@synthesize window;


- (id)init{

    self = [super init];
    if (self) {
        [[NSNotificationCenter defaultCenter] addObserver:self
          selector:@selector(applicationWillFinishLaunching:)
          name:NSApplicationWillFinishLaunchingNotification object:nil];
    }
    return self;
}

- (void) applicationWillFinishLaunching:(NSNotification *)aNotification{

    NSLog(@"applicationWillFinishLaunching");
}

-(BOOL) application: (NSApplication*)sharedApplication openFile:(NSString*) fileName {

    NSLog(@"openFile=%@", fileName);
    return YES;
}

@end
2

There are 2 answers

0
thauburger On

At least in the code provided above, you are not explicitly setting the app's delegate to be an instance of MyController. Are you setting the delegate anywhere?

Immediately following [[MyController alloc] init], try this:

[[NSApplication sharedApplication] setDelegate: mydelegate];

Without making this connection, the app won't know who is supposed to handle delegate responsibilities.

OR

The most common way to handle drag and drop onto the dock icon is to simply implement:

-(BOOL)application:(NSApplication *)sender openFile:(NSString *)path

as part of the AppDelegate class that is auto-generated for you by Xcode when you start a project.

0
pkamb On

If you have an AppleEvent event handler listening to for 'odoc' Open Document apple events:

NSAppleEventManager.shared().setEventHandler(self,
                                             andSelector: #selector(handle(event:replyEvent:)),
                                             forEventClass: AEEventClass(kCoreEventClass),
                                             andEventID: AEEventID(kAEOpenDocuments))

Then the handler will intercept the calls and the normal App Delegate methods will not be called.