使用NSButton打开Web URL - Mac OS

时间:2013-07-05 22:21:53

标签: objective-c

我需要一些特定的复制和粘贴代码的帮助来帮助我实现这一目标。我希望用户点击NSButton,它将启动safari或他们的默认Web浏览器。

我在表单上添加了一个NSButton,然后添加了声明和实现,但仍然无效。为什么不工作?在此先感谢...

 --------.h file--------
//  Copyright (c) 2013 Company. All rights reserved.
//

#import <Cocoa/Cocoa.h>
#import "HttpRequest.h"
#import "JSON.h"
#import "ChimpKit.h"
#define IS_REGISTERED @"IS_REGISTERED"
#define NORMAL_0 0
#define MAILCHIMP_1 1

@protocol RegistrationWindowDelegate

-(void) registrationDidFinished;

@end

@interface RegistrationWindowController : NSWindowController<HttpRequestDelegate,ChimpKitDelegate,NSWindowDelegate> {


    IBOutlet NSButton *pushApp1; //Newly added NSButton for opening Web URL

    IBOutlet NSWindow *registerWindow;
    IBOutlet NSWindow *privacyWindow;
    IBOutlet NSTextField *firstNameField, *lastNameField, *emailField, *verfilyEmailField;
    IBOutlet NSPopUpButton *countryPopUpBtn;
    IBOutlet NSButton *updateCheckBox, *promotionCheckBox;
    IBOutlet NSMenuItem *registerMenuItem;
    IBOutlet NSProgressIndicator *progressIndicator;
    IBOutlet NSButton *registerSoftware,*registerLater;
    id<RegistrationWindowDelegate> delegate;

}
@property(nonatomic,assign) id<RegistrationWindowDelegate> delegate;
- (id)initForRegistrationServer:(int) registrationServer withDelegate:(id<RegistrationWindowDelegate>) delegate;
+ (BOOL) isRegistered;
- (void) setRegistered:(BOOL)state;
- (void) openWindow:(id) sender;
- (BOOL)isValidEmail:(NSString *)email;
-(void) registerWithNormal;
- (void) registerWithMailChimpForApps;
- (NSArray *)addCountries;

@end

这是我的.m文件(我尝试使用网络上找到的代码片段)

--------.m file--------

//  Copyright (c) 2013 Computer. All rights reserved.
//

#import "RegistrationWindowController.h"

@interface RegistrationWindowController ()

@end

int registrationServer;

@implementation RegistrationWindowController
@synthesize delegate;

- (IBAction)pushApp1:(id)sender {

///Found this snippet on the web, but doesnt work
   NSURL *myURL = [NSURL URLWithString:@"http://www.google.com"];
   [[NSWorkspace sharedWorkspace] openURL:myURL];


  ///// Also Found this snippet on the web, but doesnt work
  // NSString *s = [ NSString stringWithFormat:@"http://www.google.com"];
  // [[NSApplication sharedApplication] openURL:[NSURL URLWithString:s]];



    }

3 个答案:

答案 0 :(得分:23)

这应该有效:

-(IBAction)pushApp1:(id)sender {
    [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"http://stackoverflow.com"]];
}

答案 1 :(得分:6)

Swift 3

的代码
@IBAction func pushApp1(_ sender: Any) {
    NSWorkspace.shared().open(URL(string: "http://stackoverflow.com")!)
}

答案 2 :(得分:0)

迅速5:

@IBAction func gotoSite(_ sender: Any) {

    if let url = URL(string: OFFICIAL_SITE_URL) {
        NSWorkspace.shared.open(url)
    }

}