Search code examples
objective-cxcodemacoscocoansworkspace

Open multiple URLs in the Browser using NSWorkspace


In my App I want to open multiple URLs in the web browser.

I do this like so:

int options = NSWorkspaceLaunchWithoutActivation | NSWorkspaceLaunchWithErrorPresentation;

[[NSWorkspace sharedWorkspace] openURLs: urls
                withAppBundleIdentifier: @"com.apple.safari"
                                options: options
         additionalEventParamDescriptor: nil
                      launchIdentifiers: nil];

Safari now only ever opens six URLs at once and when I am using the NSWorkspaceLaunchWithErrorPresentation I get the following error message:

You can’t open the application “Safari” because it is not responding.

error-message

Now when I set the bundle identifier to com.google.Chrome it is even worse and only 4 tabs are opened. Firefox (org.mozilla.firefox) opens 6 tabs as well.


Solution

  • A simple way to get around the limitation you've described would be to use a wait, or sleep function. It should allow you to open as many URLS as you decide:

    -(void)openURLs {
    
    for (int i = 0; i <= 18; i++) { // open 18 URLS for this example
    
            NSString *url = @"http://google.com";
            [self openURL:url];
    
            [NSThread sleepForTimeInterval:0.2f]; // wait .02 second
        }
    }
    
    - (void)openURL:(NSString *)url {
    
    int options = NSWorkspaceLaunchWithoutActivation | NSWorkspaceLaunchWithErrorPresentation;
    
        NSArray *urls = [NSArray arrayWithObject:[NSURL URLWithString:url]];
    
        [[NSWorkspace sharedWorkspace] openURLs: urls
                        withAppBundleIdentifier: @"com.apple.safari"
                                        options: options
                 additionalEventParamDescriptor: nil
                              launchIdentifiers: nil];
    }
    

    NOTE: Depending on how you want to load the urls (in the background, etc.) you could use a dispatch queue to load them using a separate thread.