2014-02-13 45 views
11

我想通过我的应用程序在Safari中打开Cocoa中的URL。我正在使用:通过可可应用程序在safari中打开url

[[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString: @"my url"]]; 

但问题是,如果我的默认浏览器不是Safari,那么URL会在其他浏览器中打开。但我希望我的网址只在Safari中打开。请告诉解决方案。

谢谢:)

回答

3

使用scripting bridge与Safari浏览器在Safari中打开一个网址,你会发现在打开网址的方法文件Safari.h。 要了解更多关于使用Scripting bridge的信息,请参考link并使用Safari浏览器的脚本桥,并生成Safari.h,请参阅我的answer

在Safari中打开一个URL的方法是:

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]; 
+0

它的悬而未决的文件:///当打开网址,因此url不能打开。 – Varun

+0

检查更新的答案,它现在应该工作。 – Neha

+0

是啊!这很棒! – Genevios

1

不能使用URL,你需要的NSString

if(![[NSWorkspace sharedWorkspace] openFile:fullPath 
          withApplication:@"Safari.app"]) 
    [self postStatusMessage:@"unable to open file"]; 
0

要打开一个URL与任何应用程序,你可以使用发射服务。 你想看的功能是LSOpenURLsWithRole;

编辑:
您必须将SystemConfiguration框架链接到项目此方法可用。

苹果文档的参考here

例如,如果你想打开http://www.google.com的Safari:

//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); 
} 
0
let url = URL(string:"https://twitter.com/intent/tweet")! 
NSWorkspace.shared.open([url], 
         withAppBundleIdentifier:"com.apple.Safari", 
         options: [], 
         additionalEventParamDescriptor: nil, 
         launchIdentifiers: nil) 
相关问题