【问题标题】:Open multiple URLs in the Browser using NSWorkspace使用 NSWorkspace 在浏览器中打开多个 URL
【发布时间】:2015-05-29 00:04:40
【问题描述】:

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

我是这样做的:

int options = NSWorkspaceLaunchWithoutActivation | NSWorkspaceLaunchWithErrorPresentation;

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

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

您无法打开应用程序“Safari”,因为它没有响应。

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

【问题讨论】:

  • 你要打开多少个url?
  • 嗯,肯定不止六个。也许十个,也许三十个。我认识的一些人总是打开大量的标签,所以我认为六个非常有限。
  • 没错,也许是一次性方法限制了它;在六次迭代后尝试做一个sleep(1);if (i == 6) sleep(1); 刚刚尝试过,它就可以工作——即使它看起来很老套。把它放在一个调度队列中是无缝的——甚至没有注意到sleep(1)
  • 好的,感谢您的研究。我会调查一下。如果您将您的方法作为答案发布,我将很乐意接受。
  • 我很乐意。我也会把一个更好的例子放在一起:)

标签: objective-c xcode macos cocoa nsworkspace


【解决方案1】:

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

-(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 的方式(在后台等),您可以使用调度队列使用单独的线程加载它们。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-27
    • 1970-01-01
    • 2014-12-06
    • 2014-02-10
    • 2021-07-12
    • 1970-01-01
    相关资源
    最近更新 更多