Skip to content

Instantly share code, notes, and snippets.

@olierxleben
Created March 15, 2015 16:53
Show Gist options
  • Save olierxleben/39807aa6a3526d5ad467 to your computer and use it in GitHub Desktop.
Save olierxleben/39807aa6a3526d5ad467 to your computer and use it in GitHub Desktop.
Code demonstrated how to load local files into WKWebView - Result works in Simulator, not on device (Tested with 8.2, iPhone 6)
// Code wor
import UIKit
import WebKit
class ViewController: UIViewController, WKScriptMessageHandler {
var webView = WKWebView()
var contentController = WKUserContentController()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
var path = NSBundle.mainBundle().pathForResource("index", ofType: "html")
var url = NSURL(fileURLWithPath: path!)
//var request = NSURLRequest(URL: url!)
var text = String(contentsOfFile: path!, encoding: NSUTF8StringEncoding, error: nil)
var theConfiguration = WKWebViewConfiguration()
contentController.addScriptMessageHandler(self, name: "callbackHandler")
theConfiguration.userContentController = contentController
webView = WKWebView(frame: self.view.frame, configuration: theConfiguration)
//webView.loadRequest(request)
webView.loadHTMLString(text!, baseURL: url)
self.view.addSubview(webView)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) {
if(message.name == "callbackHandler") {
println("JavaScript is sending a message \(message.body)")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment