Tips For WKWebView That Will Keep You From Going Troubles

dakeshi
2 min readMar 17, 2016

--

Recently, I replace all of UIWebView with WKWebView in my projects. I’d like to share my experiences for developers want to use WKWebView.

WKWebView is faster, more stable than UIWebView. With enhanced JavaScript supports, you can inject custom JS in the specific web pages. And you can display alertView in response to JavaScript functions alike alert, confirm through WKUIDelegate. Isn’t it Cool?

I’ll show you some situations you can encounter with sample codes and short comments.

Cache, Cache, Cache….Crash.

You have to know about cache issues if you consider to use WKWebView in your app. You’ll encounter this kind of customer reviews when you release your app with an default configuration of WKWebView.

“Your app have increased indefinitely. I don’t have enough storage.”

Creation of WKWebView with an default configuration will save all of cache data in your app. How to avoid this situation? Unfortunately, there are no property or method to stop this. Alternatively, you can check your web data size and call trigger to clean internal data. Or create a setting menu to clear cache data. The following are one of example codes from Firefox iOS projects:

https://github.com/mozilla/firefox-ios/blob/master/Client/Frontend/Settings/Clearables.swift

tel, sms, mailto tags and app store link

These tags and app store link are not connect automatically to the appropriate app in WKWebView. So, you have to write an addition code to deal with them.

To speed up the process, you can check navigationAction.navigationType equal to .LinkActivated before the switch statement.

WKUIDelegate

It has not enough information about WKUIDelegate yet, but it is very useful to display native UI in response to JavaScript. It has three method to support JavaScript :

For example, when you press login button without username and password, most of webpages send an alert message. In JavaScript, it will be popup box.(alert, confirm box).

You have to confirm WKUIDelegate protocol to use these methods.

Open New Window

How to open new WebView with JavaScript’s window open function or target = _blank tags? I think that there are three options to do that. Optionally, SFSafariViewController would be another choice.

  1. make new WKWebView and open new webpage
  2. open Safari app
  3. catch the JS and request load again with new webpage in the same WKWebView

I prefer to open Safari app because we can return easily the original app without press Home button.

Conclusion

Although you have to do some extra works depend on what your needs, WKWebKit is good choice to provide web browsing in your application. So, practice it and enjoy it.:)

I would be happy that this post can make you better understanding WKWebView.

references

--

--

dakeshi

software developer and tech writer/korean translator.