Reputation: 91
I am working on a project with WKWebView and I have the html loading from the local project. JavaScript is working as expected, but when I try to use a class it makes the WebView just appear blank.
I have tried using ES6 syntax and ES5 syntax they both cause the same problem. Is there a way to use JavaScript classes in a local html file in WKWebView? If there is what am I doing wrong?
This is my code for the WebView application
import UIKit
import WebKit
class ViewController: UIViewController {
let webView = WKWebView()
let remoteAccess = false
let url = "Website/index"
override func loadView(){
if(remoteAccess){
loadWebView(string: url)
}else{
loadLocalWebView(string: url)
}
self.view = webView
}
override var prefersStatusBarHidden: Bool{
return true;
}
override func viewDidLoad() {
super.viewDidLoad()
}
func loadWebView(string: String){
if let url = URL(string: string){
let request = URLRequest(url: url);
webView.load(request)
}else{
print("Failed to connect to URL: " + string)
}
}
func loadLocalWebView(string: String){
if let url = Bundle.main.url(forResource: string, withExtension: "html"){
webView.loadFileURL(url, allowingReadAccessTo: url.deletingLastPathComponent())
}else{
print(string + "not found!")
}
}
}
this is the code for the html file
<!DOCTYPE html>
<html>
<head>
<title>Local Demo</title>
<meta name="viewport"
content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css"
href="index.css" />
</head>
<body>
<script>
var display = new Display(window.innerWidth,window.innerHeight);
var ctx = display.create();
function render(){
ctx.fillRect(0,0,100,100);
requestAnimationFrame(render);
}
render();
function Display(width,height){
this.canvas = document.createElement("canvas");
this.canvas.id = "canvas";
this.canvas.width = width;
this.canvas.height = height;
}
Display.prototype.create = function(){
document.body.appendChild(this.canvas);
this.ctx = canvas.getContext("2d");
return this.ctx;
}
</script>
</body>
Upvotes: 0
Views: 837
Reputation: 91
Turns out the problem, was that I was defining the class after creating the instance, which caused nothing to work, after flipping the order, everything worked.
Upvotes: 1