Search code examples
objective-cmacoscocoadefaultnsurl

Get macOS default browser name - LSCopyDefaultApplicationURLForContentType


I am developing a macOS application in Xcode. One of the things I need to do, is to open URL's the system detault web browser. I have an alert that pops up that gives the user this option. The alert is supposed to show the name of the default web browser. However I am unable to figure out the name of the default web browser.

I have the tried the following code:

NSLog(@"%@", LSCopyDefaultApplicationURLForContentType(kUTTypeURL, kLSRolesAll, nil));

It just returns file:///Applications/Opera.app/ even though my default browser is set to Safari. Not matter what I change my default browser to (Chrome, Safari, Firefox, etc...), the above method just returns the URL for Opera browser.

Does anyone know how I can find out what the name of the default browser is? I know how to open URL's in the default browser, thats very easy, but getting the name of the default browser isn't.

I know this is possible because apps like Tweetbot, have an option saying "Open in Safari" which changes to whatever you default browser is.

Thanks for your time, Dan.


Solution

  • You can use [[NSWorkspace sharedWorkspace] open:url] to open any URL in the default browser and [[NSWorkspace sharedWorkspace] URLForApplicationToOpenURL: url] to get the URL for the default application for a given URL.

    To get the app name, try [[NSBundle bundleWithURL:appUrl] objectForInfoDictionaryKey:@"CFBundleDisplayName"] or [[NSBundle bundleWithURL:appUrl] objectForInfoDictionaryKey:@"CFBundleName"] if the first is null. If both fail, [appUrl deletingPathExtension] lastPathComponent] can be used as a last resort.

    See the docs here:

    https://developer.apple.com/documentation/appkit/nsworkspace/1533463-openurl?language=objc

    https://developer.apple.com/documentation/appkit/nsworkspace/1533391-urlforapplicationtoopenurl?language=objc

    https://developer.apple.com/documentation/foundation/nsbundle/1408696-objectforinfodictionarykey?language=objc