如何在WebView(OSX项目)中启动时加载URL?

时间:2013-04-10 09:28:08

标签: objective-c macos webview

我刚刚开始开发mac应用程序,我想在应用程序启动时将WebView作为URL。这是我的代码:

AppDelegate.h

#import <Cocoa/Cocoa.h>
#import <WebKit/WebKit.h>

@interface AppDelegate : NSObject <NSApplicationDelegate> {
     WebView *myWebView;
    //other instance variables
}

@property

(retain, nonatomic) IBOutlet WebView *myWebView;

//other properties and methods

@end

AppDelegate.m

 #import "AppDelegate.h"
#import <WebKit/WebKit.h>

@implementation AppDelegate

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    NSString *urlText = @"http://google.com";
    [[self.myWebView mainFrame] loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlText]]];
    return;
    // Insert code here to initialize your application
}

@end

如何在WebView(OSX项目)中启动时加载URL?

我认为代码可以工作但是当我尝试在Interface Builder中将代码与WebView连接时,我无法在插座列表中找到“Web视图”。 谢谢 我在最后一篇文章后更新了我的代码,但仍然无效。 再次感谢您的回复。

2 个答案:

答案 0 :(得分:7)

您需要添加WebKit框架。enter image description here

#import <WebKit/WebKit.h>

enter image description here

答案 1 :(得分:6)

很难确定这里的问题是什么,所以猜猜......

您在IB中拖动连接的方式是什么?

要连接插座,您需要从检查器中显示的插座拖动到网络视图:

making the connection

如果您以另一种方式拖动,从网页视图到大纲中的App Delegate,您正尝试连接操作。

您的代码中也存在问题:实例变量:

@interface AppDelegate : NSObject <NSApplicationDelegate>
{
   WebView *myWebView;
   //other instance variables
}

将不会被您的财产使用:

@property (retain, nonatomic) IBOutlet WebView *myWebView;

因为您的属性是自动合成的,因此将创建一个实例变量_myWebView。您应该看到编译器警告此效果。

这反过来意味着声明:

[[myWebView mainFrame] loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlText]]];

将无法满足您的期望,因为myWebView将为nil而不会引用您的WebView。您应该将该属性称为self.myWebView

[[self.myWebView mainFrame] loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlText]]];

通过这些更改,您应该在网络视图中看到Google。

HTH