使用 NSWorkspace 在浏览器中打开多个 URL

Open multiple URLs in the Browser using NSWorkspace

在我的应用程序中,我想在网络浏览器中打开多个 URL。

我是这样做的:

int options = NSWorkspaceLaunchWithoutActivation | NSWorkspaceLaunchWithErrorPresentation;

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

Safari 现在一次只能打开六个 URL,当我使用 NSWorkspaceLaunchWithErrorPresentation 时,我收到以下错误消息:

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

现在,当我将包标识符设置为 com.google.Chrome 时,情况更糟,只打开了 4 个选项卡。 Firefox (org.mozilla.firefox) 也打开 6 个标签页。

绕过您描述的限制的一种简单方法是使用等待或睡眠功能。它应该允许您打开任意数量的 URLS:

-(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];
}

注意:根据您想要加载 url 的方式(在后台等),您可以使用调度队列使用单独的线程加载它们。