2014-02-13 48 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) 
相關問題