June 12, 2014
Swift Hybrid Development
My doctoral degree is now done. I could begin supporting that code set again but it would be better to implement it in Swift or current Objective-C and gain access to the new WebKit API common to both iOS 8 and OS X Yosemite. Another reason to ‘start from scratch’ is that the new WKWebView is much more powerful that the old UIWebView. According to Apple, it has all the new HTML 5 abilities and now the same webkit engine as Safari so tools like QC Hybrid, PhoneGap, and the other hybrid tools are not needed by the vast majority of Hybrid developers. That was not true in the past. Never the less, I maintain that this type of project should, in most cases, be a temporary and stop-gap solution while you develop your app in the native languages of the platform. At least for now.
With all that history out of the way, lets get to a Swift code example.
You can see I have a file called index.html. This is the file that the example code is going to load and trigger the loading of the main.css and main.js files just like any normal web page.
In the project’s ViewController.viewDidLoad() method I inserted added code to create a WKWebView, load index.html, and add the WKWebView to the main view.
(Note: This code example has been updated for Swift 2.0 on my gitHub repository.)
//get a string path to the file var path = NSBundle.mainBundle().pathForResource("index", ofType: ".html") //create a URL for the path var url = NSURL(fileURLWithPath:path) //create a request for the URL var request = NSURLRequest(URL:url) //create the WKWebView and set the size to match //the window's full view var theWebView:WKWebView = WKWebView(frame:self.view.frame) //have the web view load the page theWebView.loadRequest(request) //add the web view to the main view self.view.addSubview(theWebView)
The reason I started the load before adding the web view was to get a little buffering going on before the display. The web view will load without being displayed.