7

I have a Mac OS X application that implements the -(void)application openFiles: method to react to dragged files on the application icon.

I have a list of allowed filetypes in the document types section of my target info settings and the Finder indeed allows drags, but when a PDF is in the list of dragged items, my delegate method is called twice: one for all the elements without the PDF, and one for the PDF alone.

This of course makes it impossible for me to handle the situation properly.

Can anybody help me or explain what is happening? Thanks

pkamb
  • 33,281
  • 23
  • 160
  • 191
Alfonso Tesauro
  • 1,730
  • 13
  • 21
  • Possible duplicate of [Application:openFiles: separate files by groups](https://stackoverflow.com/questions/3664240/applicationopenfiles-separate-files-by-groups) – Ssswift Jun 22 '17 at 00:47

1 Answers1

11

I've seen this behavior in one of my apps (usually when dragging a whole bunch of files at one time). As I workaround, instead of opening the files directly from application:openFiles:, I queue them up and open the queued files after a small delay. Something like the following:

- (void) application:(NSApplication*)sender openFiles:(NSArray*)filenames
{
    // I saw cases in which dragging a bunch of files onto the app
    // actually called application:openFiles several times, resulting
    // in more than one window, with the dragged files split amongst them.
    // This is lame.  So we queue them up and open them all at once later.
    [self queueFilesForOpening:filenames];

    [NSApp replyToOpenOrPrint:NSApplicationDelegateReplySuccess];
}


- (void) queueFilesForOpening:(NSArray*)filenames
{
    [self.filesToOpen addObjectsFromArray:filenames];
    [self performSelector:@selector(openQueuedFiles) withObject:nil afterDelay:0.25];
}


- (void) openQueuedFiles
{
    if( self.filesToOpen.count == 0 ) return;

    [self makeNewWindowWithFiles:self.filesToOpen];

    [self.filesToOpen removeAllObjects];
}
zpasternack
  • 17,838
  • 2
  • 63
  • 81
  • 2
    Thanks a lot zpasternack ! strange behaviour however ! – Alfonso Tesauro Jun 06 '16 at 18:51
  • 3
    Absolutely ridiculous behaviour. Having trouble with this myself. – svth May 06 '17 at 15:04
  • Me too. I only get it for the first file I try to import. Any subsequent imports just issue the single call. – RichS Oct 29 '17 at 21:25
  • FWIW, I used a similar approach but with a NSMutableSet to automatically remove duplicates. – RichS Oct 29 '17 at 21:36
  • 5
    I'd recommend using a non-repeating `NSTimer` instead of `-performSelector:withObject:afterDelay` because you can cancel the timer on subsequent `-application:openFiles:` calls to reset the open queued files delay. This way your `-openQueuedFiles` call is only called once inside your timer delay timeframe. – Andrew Aug 04 '18 at 21:21