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:
openURL
NSWorkspace
[[ 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:
LSOpenFromURLSpec
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:
openURLs: withAppBundleIdentifier: options: additionalEventParamDescriptor: launchIdentifiers:
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.
This entry was posted Friday, 27th October, 2006 at 8:47 am and is filed under cocoa, mac os x, programming. You can leave a response, or trackback from your own site.
how to open url any website inforemation please replay. thank
how to open url any webside please give me information thankns
Name (required)
Mail (will not be published) (required)
Website
uDecide! ... because the important decisions are hard enough.
NewsHawker: Your own personal news anchor.
September 17th, 2007 at 6:00 am
how to open url any website inforemation please replay.
thank
September 17th, 2007 at 6:03 am
how to open url any webside please give me information thankns