Xcode 4.5 - OS X Cocoa Application - Basic WebView: Google Load on Open
I am trying to create an extremely basic OS X Cocoa Application that loads http://www.google.com when opened . As basic as possible (no back or forward buttons, etc.).
I have little experience with Xcode 4.5 and cannot find webview tutorials 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 not very far.
Here's what I've done so far:
- Created a new OS X Cocoa app in Xcode 4.5.2
- Added WebView object for Window object
Based on the iOS Web UI tutorial, I am guessing all I have to do is add a couple of lines of code and should it 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 all night.
source to share
After adding WebView
to the main window, you must make sure you add WebKit.framework
the linked structures and libraries for your project, otherwise you will get a link error.
.h:
@class WebView;
@interface MDAppDelegate : NSObject <NSApplicationDelegate>
@property (weak) IBOutlet WebView *webView;
@property (assign) IBOutlet NSWindow *window;
@end
Assuming you've created a IBOutlet
for WebView
with a name WebView
like the code above, you can load the url using the following code:
.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
source to share
add keyword self
to next line
[myWebView loadRequest:myRequest];
like this
[self.myWebView loadRequest:myRequest];
try the following code, it works for me, just tested
1) create a new project
2) select ViewController, go to xcode menu Editor-
> Insert In / "> Navigation Controller
3) declare myWebView property in ViewController.h
in ViewController.m write the 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];
source to share