When working on a Cordova Hybrid app (a cordova app wrapped in a thin layer of native UI) that uses Ionic Web View plugin as the WebView, there was a requirement from the client to have a native button that would load a local testing html file in the main WebView.
Changing the main WebView url in response to a native button, requires editing the MainViewController.m
file, which is the main view in which the WebView lives, and where we can find its reference: self.webViewEngine
.
Our VC’s self.webViewEngine
exposes the loadRequest
method, which we can call to load any url that we’ve allowed using allow-navigation
tag in config.xml
. Therefor, calling loadRequest
with @"test.html"
should be quite straightforward right? Not exactly. Loading @"test.html"
will show a white screen, with no error, even though the file exists in the www
folder right next to index.html
.
So following my commitment to blog about anything that takes me more than half an hour to solve, you’re now reading this post, which will hopefully save you some time.
According to Ionic docs, the Ionic Web View uses a local HTTP server to serve local files, including the main index.html
. This is different from the default Cordova WebView that loads index.html
with the file:///
protocol. Under the hood, Ionic Web View engine adds handling of the custom url scheme ionic://
, using WKWebView’s WKURLSchemeHandler.
There’s some tricky logic that goes into resolving different url protocols, including replacing file:///
protocol. So in order to access local files that are bundled within our www
folder, we’ll use this ionic://
protocol directly.
This is how to load test.html
into the main Ionic Web View (which in turn can load any local JS / CSS / other resource). You can use this code in MainViewController.m
in the XCode project.
NSURL *url = [NSURL URLWithString:@"ionic://localhost/test.html"]
NSURLRequest* appReq = [
NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:20.0
];
[self.webViewEngine loadRequest:appReq];
We’re creating an NSURL
that points to ionic://localhost/test.html
, then creating an NSURLRequest
with that url and a timeout of 20 seconds, then calling the method loadRequest
of self.webViewEngine
(inherited from CDVViewController
).
Now your new URL should load in the WebView!