Updating from UIWebview to WKWebView in Native iOS Xamarin Apps – Part 1

Stay tuned, folks. This post will be updated with screenshots and a sample solution soon. 🙂

With the update to iOS 11, I was using a UIWebView and found that suddenly, many native iOS user controls didn’t work, or were behaving strangely. I changed to a WKWebView, but as it works in development, sometimes fixing one problem can introduce others. It turned out that while changing to a WKWebView made the user controls on the page work fine, some elements like external links were suddenly unclickable, and the app crashed when opening the camera or file system.

To fix the links, I had to add a NavagtionDelegate, something I didn’t need to do when I was using a UIWebView.

To fix the camera situation, I had to add a prompt asking the user for permission to use the camera. It actually gave me more peace of mind from a user experience and security perspective. News stories are good at terrifying users about their cameras being commandeered by rogue apps. It gives users some peace of mind to know that the app is letting them know it will be accessing the camera. To add the prompt, I added a setting to the info.plist. I made sure to also add it for accessing the file system and photo gallery. I added an example of this below. They were relatively simple fixes, but not very intuitive ones.

So I wondered, what else is there to know about WKWebView? I can’t be the only one switching over from UIWebView to WKWebView, and it’s a common Xamarin component, since lots of people make apps as either a shell for a web app that’s already published or as a view that connects from app content to a published web app.

Here’s some things that are nice about WKWebView:

  1. It uses the JavaScript that Safari does, so you don’t have to import a bunch of extra code or components into your project to use it. The result is faster load times for pages viewed within it.
  2. Navigation must include a full URI or use a Navigation Delegate (in the case of my external links problem.).
  3. You can navigate backwards and forwards with the WKBackForwardList.
  4. WKUserContentController allows JavaScript to pose messages and apply user scripts to pages viewed within the WKWebView.

Mattt Thompson gives a good description of the difference between WKWebView and UIWebView methods that I will definitely be saving for later as I build out my app.

I’ll be posting a part 2 to this article this weekend. I’m currently recovering from a cold. Hope to see you back soon. Best of luck in your iOS development. 🙂

Other Sources:

Hudson, Paul. 2018. What’s the Difference Between UIWebView and WKWebView? https://www.hackingwithswift.com/example-code/wkwebview/whats-the-difference-between-uiwebview-and-wkwebview

Apple, Inc. 2017. WKWebView. https://developer.apple.com/documentation/webkit/wkwebview

Leave a Reply