Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading Multiple Dragged-n-Dropped Files

I have a small window inside the main xib (MainMenu.xib) with an NSImageView control for an OS X application. This view control has an NSImageView subclass that is supposed to accept files that the user brings (drag n drop). Since I have no experience in developing a Mac application with Objective-C, I've searched around, checking out some sample projects from Apple, and got some idea. Well, to make the story short, I've just copied the code posted here. It works. Great... The following is a concise version.

- (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender{
    return NSDragOperationCopy;
}

- (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)sender{
}

- (void)draggingExited:(id <NSDraggingInfo>)sender{
}

- (BOOL)prepareForDragOperation:(id <NSDraggingInfo>)sender{
    return YES; 
}

- (BOOL)performDragOperation:(id<NSDraggingInfo>)sender {
    NSPasteboard *pboard = [sender draggingPasteboard];
    if ([[pboard types] containsObject:NSURLPboardType]) {
        NSURL *fileURL = [NSURL URLFromPasteboard:pboard];
        NSLog(@"Path: %@", [self convertPath:fileURL]); // <== That's just what I need
    }
    return YES;
}

- (NSString *)convertPath:(NSURL *)url {
    return url.path;
}

For now, the drop box only gets file paths one at a time regardless of the number of files the user drags and drops onto the drop box. So what I would like to know is how to get the application to read all multiple files the user brings.

Thank you,

like image 678
El Tomato Avatar asked Dec 04 '22 11:12

El Tomato


2 Answers

Change your performDragOperation: method to this:

- (BOOL)performDragOperation:(id<NSDraggingInfo>)sender {
    NSPasteboard *pboard = [sender draggingPasteboard];
    if ([[pboard types] containsObject:NSURLPboardType]) {
        NSArray *urls = [pboard readObjectsForClasses:@[[NSURL class]] options:nil];
        NSLog(@"URLs are: %@", urls); 
    }
    return YES;
}
like image 113
rdelmar Avatar answered Dec 28 '22 03:12

rdelmar


Swift Style:

override func performDragOperation(sender: NSDraggingInfo) -> Bool 
{
    if let board = sender.draggingPasteboard().propertyListForType(NSFilenamesPboardType) as? NSArray 
    {              
        for imagePath in board
        {
            if let path = imagePath as? String
            {
                 println("path: \(path)")
            }
        }                
        return true               
    }
    return false
}
like image 39
Peter Kreinz Avatar answered Dec 28 '22 04:12

Peter Kreinz