【发布时间】:2018-05-07 20:04:43
【问题描述】:
我只想通过我在 Safari 中的应用程序在 Cocoa 中打开一个 URL。我正在使用:
[[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString: @"my url"]];
但问题是,如果我的默认浏览器不是 Safari,那么 URL 会在其他浏览器中打开。但我希望我的 URL 只在 Safari 中打开。请告诉解决方法。
谢谢:)
【问题讨论】:
我只想通过我在 Safari 中的应用程序在 Cocoa 中打开一个 URL。我正在使用:
[[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString: @"my url"]];
但问题是,如果我的默认浏览器不是 Safari,那么 URL 会在其他浏览器中打开。但我希望我的 URL 只在 Safari 中打开。请告诉解决方法。
谢谢:)
【问题讨论】:
let url = URL(string:"https://twitter.com/intent/tweet")!
NSWorkspace.shared.open([url],
withAppBundleIdentifier:"com.apple.Safari",
options: [],
additionalEventParamDescriptor: nil,
launchIdentifiers: nil)
【讨论】:
let url = NSURL(string:"http://example.com")!
let browserBundleIdentifier = "com.apple.Safari"
NSWorkspace.sharedWorkspace().openURLs([url],
withAppBundleIdentifier:browserBundleIdentifier,
options:nil,
additionalEventParamDescriptor:nil,
launchIdentifiers:nil)
【讨论】:
使用scripting bridge和safari在safari中打开一个URL,你会在文件Safari.h中找到打开url的方法。
要了解有关使用 Scripting bridge 的更多信息,请参阅 link 并在 safari 中使用脚本桥并生成 Safari.h,请参阅我的 answer 此处。
在Safari中打开网址的方法是:
NSDictionary *theProperties = [NSDictionary dictionaryWithObject:@"https://www.google.co.in/" forKey:@"URL"];
SafariDocument *doc = [[[sfApp classForScriptingClass:@"document"] alloc] initWithProperties:theProperties];
[[sfApp documents] addObject:doc];
[doc release];
【讨论】:
你不能使用 URL,你需要一个 NSString
if(![[NSWorkspace sharedWorkspace] openFile:fullPath
withApplication:@"Safari.app"])
[self postStatusMessage:@"unable to open file"];
【讨论】:
要使用任何应用程序打开 URL,您可以使用启动服务。
你想看的函数是LSOpenURLsWithRole;
编辑:
您必须将 SystemConfiguration 框架链接到您的项目才能使用此方法。
苹果文档参考here
例如,如果你想用 safari 打开http://www.google.com:
//the url
CFURLRef url = (__bridge CFURLRef)[NSURL URLWithString:@"http://www.google.com"];
//the application
NSString *fileString = @"/Applications/Safari.app/";
//create an FSRef of the application
FSRef appFSURL;
OSStatus stat2=FSPathMakeRef((const UInt8 *)[fileString UTF8String], &appFSURL, NULL);
if (stat2<0) {
NSLog(@"Something wrong: %d",stat2);
}
//create the application parameters structure
LSApplicationParameters appParam;
appParam.version = 0; //should always be zero
appParam.flags = kLSLaunchDefaults; //use the default launch options
appParam.application = &appFSURL; //pass in the reference of applications FSRef
//More info on params below can be found in Launch Services reference
appParam.argv = NULL;
appParam.environment = NULL;
appParam.asyncLaunchRefCon = NULL;
appParam.initialEvent = NULL;
//array of urls to be opened - in this case a single object array
CFArrayRef array = (__bridge CFArrayRef)[NSArray arrayWithObject:(__bridge id)url];
//open the url with the application
OSStatus stat = LSOpenURLsWithRole(array, kLSRolesAll, NULL, &appParam, NULL, 0);
//kLSRolesAll - the role with which the applicaiton is to be opened (kLSRolesAll accepts any)
if (stat<0) {
NSLog(@"Something wrong: %d",stat);
}
【讨论】:
产生一个进程并执行 open -a "Safari" http://someurl.foo 也可以解决问题
【讨论】: