Reputation: 6606
I am developing a macOS application in Xcode. One of the things I need to do, is to open URLs the system default 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.
How can I find out what the name of the default browser is? I know how to open URLs in the default browser, that's 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.
Upvotes: 3
Views: 2959
Reputation: 61
//given a fileUrl
CFURLRef helperApplicationURL = LSCopyDefaultApplicationURLForURL((__bridge CFURLRef)fileUrl, kLSRolesAll, NULL);
if (helperApplicationURL != NULL) {
NSString *helperApplicationPath = [(__bridge NSURL *)helperApplicationURL path];
NSString *helperApplicationName = [[NSFileManager defaultManager] displayNameAtPath:helperApplicationPath];
CFRelease(helperApplicationURL);
if ([helperApplicationName containsString:@".app"]) {
helperApplicationName = [helperApplicationName stringByDeletingPathExtension];
}
return helperApplicationName;
}
Upvotes: 0
Reputation: 6380
Using the accepted answer on Swift 5
var defaultBrowser: String? {
NSWorkspace.shared.urlForApplication(toOpen: URL(string: "http://")!)
.flatMap(Bundle.init(url:))
.flatMap {
$0.object(forInfoDictionaryKey: "CFBundleDisplayName") ?? $0.object(forInfoDictionaryKey: "CFBundleName")
}.flatMap {
$0 as? String
}
}
Upvotes: 1
Reputation: 2477
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
Upvotes: 6
Reputation: 285082
Try the other LaunchServices method LSCopyDefaultApplicationURLForURL
and pass the http
scheme
CFURLRef httpURL = CFURLCreateWithString(kCFAllocatorDefault, CFSTR("http://"), NULL);
NSLog(@"%@", LSCopyDefaultApplicationURLForURL(httpURL, kLSRolesAll, nil));
Upvotes: 2