I’m trying to create simple OS X app (not iOS) with a web viewer using the new WKWebView
and the Swift language. I’m hoping to take advantage of the faster performance of the WKWebView
class.
In the projects AppDelegate.swift file I have the following code:
import Cocoa
import WebKit
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
@IBOutlet weak var window: NSWindow!
@IBOutlet var containerView : NSView! = nil
var webView: WKWebView?
var url = NSURL(string:"http://www.google.com/")
var req = NSURLRequest(URL: url)
self.webView!.loadRequest(req)
}
In the MainMenu.xib file I have added a Custom View object to the main window and linked it to the @IBOutlet var containerView
.
I’m getting error messages on the last two lines of code:
var req = NSURLRequest(URL: url)
‘AppDelegate. Type’ does not have a member named ‘url’
self.webView!.loadRequest(req)
Expected declaration
Any help would be most appreciated.
This took me a while to figure out.
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
@IBOutlet weak var window: NSWindow!
var viewController : ViewController!
func applicationDidFinishLaunching(aNotification: NSNotification) {
self.viewController = ViewController(nibName:"ViewController", bundle:nil)
self.window.contentView = self.viewController!.view
self.window.contentViewController = self.viewController!
self.viewController!.view.frame = self.window.contentView.bounds;
}
...
}
This essentially replaces whatever is in my NSWindow
with the view and view controller of my own making. My implementation of the ViewController
class looks like this:
import Cocoa
import WebKit
class ViewController: NSViewController {
var webView: WKWebView?
override func loadView() {
self.webView = WKWebView()
self.view = self.webView!
var url = NSURL(string:"http://www.google.com/")
var req = NSURLRequest(URL: url!)
self.webView!.loadRequest(req)
}
}
So essentially what happens is that I create a custom view controller that sets the WKWebView
as its view, and then I set it and its view to the NSWindow
view controller and view.
Move the last three lines (declaring url
, req
and loading the request) into a method on AppDelegate, like applicationDidFinishLaunching:
(similar to what @MinnesotaSteve's answer suggests). You cannot have top-level statements like that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With