Open URL in Background

I wanted to programatically open a URL in the associated application. I started in Xcode’s Developer Documentation and searched for openURL which seemed like a good method name. I found the NSWorkspace class’ openURL method. I love it when that happens. One line of code later and I was opening URLs:


[[ NSWorkspace sharedWorkspace ] openURL : url ];

However, I immediately realized that this method results in the application associated with the URL becoming the active application which is not what I want. So, I was off to my next reference, Google. I quickly found two relevant references. Brent Simmons’ blog mentioned using LSOpenFromURLSpec to open a URL in the background. Karelia Software actually had code to do exactly what I wanted. I simplified it for my particular need:


NSArray* urls = [ NSArray arrayWithObject:
      [ NSURL URLWithString:url ]];

LSLaunchURLSpec urlSpec;
urlSpec.appURL = NULL /* use default application */;
urlSpec.itemURLs = ( CFArrayRef )urls;
urlSpec.passThruParams = NULL;
urlSpec.launchFlags = kLSLaunchDontSwitch;
urlSpec.asyncRefCon = NULL;

OSStatus status = LSOpenFromURLSpec( &urlSpec,
      NULL /* outLaunchedURL */ );

Perfect. However, I was surprised there wasn’t a way to do this with the Cocoa framework. I dug a bit deeper (well, not that much deeper it was the next method in the NSWorkspace documentation) and found the NSWorkspace class’ openURLs: withAppBundleIdentifier: options: additionalEventParamDescriptor: launchIdentifiers: method. The length of its name probably kept me from reading about it in the first place. Regardless, it is exactly what I wanted. The final implementation to open a URL in the background:


NSArray* urls = [ NSArray arrayWithObject:
      [ NSURL URLWithString:url ]];

BOOL opened = [[ NSWorkspace sharedWorkspace ]
      openURLs:urls
      withAppBundleIdentifier:nil
            /* use default system bindings */
      options:NSWorkspaceLaunchWithoutActivation
      additionalEventParamDescriptor:nil
      launchIdentifiers:nil ];

Short and sweet.

2 Responses to “Open URL in Background”

  1. shamim Says:

    how to open url any website inforemation please replay.
    thank

  2. shamim Says:

    how to open url any webside please give me information thankns

Leave a Reply

thoughts yet to be boiled down to their essence

ukraine, apartment kiev for rent | Catch your occasion to try elegant ladies rado replica watches in http://www.buy-replica.com | chicas desnudas en adultq.net