Xcode 4.5 - OS X Cocoa Application - Basic Web View: Load Google when opened

不问归期 提交于 2019-12-06 07:36:04

问题


I'm trying to create an extremely basic OS X Cocoa Application that when opens loads http://www.google.com. As basic as possible (no back or forward buttons, etc.).

I have little experience with Xcode 4.5 and I can't find any tutorials regarding a web view for OS X Cocoa Application AND Xcode 4.5. I was able to find a tutorial and create a web view for an iOS web view. I took what I learned but didn't get very far.

Here's what I did so far:

  • Created New OS X Cocoa Application in Xcode 4.5.2
  • Added a WebView object to the Window object

Based on the iOS web view tutorial I assume all I need to do is add a couple lines of code and it should work?

This is the code I used in the iOS web view (ViewController.m):

NSURL *myURL = [NSURL URLWithString:@"http://www.google.com"];

NSURLRequest *myRequest = [NSURLRequest requestWithURL:myURL];

[myWebView loadRequest:myRequest];

Any help would be much appreciated. I've been stuck on this all night.


回答1:


After adding the WebView to your main window, you'll want to make sure you've added the WebKit.framework to the Linked Frameworks and Libraries for your project otherwise you'll get a linking error.

.h:

@class WebView;

@interface MDAppDelegate : NSObject <NSApplicationDelegate>

@property (weak) IBOutlet WebView *webView;
@property (assign) IBOutlet NSWindow *window;

@end

Assuming you've created an IBOutlet for the WebView named webView like in the code above, you can load a URL using the code below:

.m:

@implementation MDAppDelegate

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
    NSURLRequest *request = [NSURLRequest requestWithURL:
                 [NSURL URLWithString:@"https://www.google.com/"]];
    [self.webView.mainFrame loadRequest:request];
}

@end

Sample GitHub project: https://github.com/NSGod/WebViewFinagler




回答2:


add self keyword to following line

[myWebView loadRequest:myRequest];

like this

[self.myWebView loadRequest:myRequest];

try following code,it work for me,just tested

1) create new project
2) select ViewController ,goto xcode menu
Editor->Embed in->Navigation controller
3)declare myWebView property in ViewController.h

in ViewController.m write following code

   self.myWebView = [[UIWebView alloc] initWithFrame:self.view.bounds]; 
   self.myWebView.scalesPageToFit = YES;
   [self.view addSubview:self.myWebView];
   NSURL *myURL = [NSURL URLWithString:@"http://www.google.com"];
   NSURLRequest *myRequest = [NSURLRequest requestWithURL:myURL];
   [self.myWebView loadRequest:myRequest];


来源:https://stackoverflow.com/questions/14474142/xcode-4-5-os-x-cocoa-application-basic-web-view-load-google-when-opened

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!