WKWebView iOS Tutorial
Hi, In today’s post, we’ll learn how to use WKWebView or simply saying, how to implement web view in iOS applications. I am using Xcode 9 and Swift 4 for this tutorial. So, let’s do it using our step by step approach:
Open Xcode and create a Single View Application.
Give some name to your app, eg. WebViewAppTutorial and make sure to choose Swift as the language, click Next.
Here, first we’ll embed our app in a navigator controller. For this, just open your Main.storyboard and click on View Controller. Now, select Editor from Xcode Menu bar, and select Embed in > Navigation Controller.
Now, open ViewController.swift file and import webkit module.
Under your ViewController class , add the webView property as:
Now, in your class declaration, add one WKNavigationDelegate protocol as shown below:
Add loadView() method in your View Controller:
Now, in viewDidLoad() method, add following lines of code:
Now, Implement webView(:didFinish:) method:
This will add the website’s title on the title bar when your website will be loaded in the app.
That’s it, you can now run the app and web page will be displayed in the app instantly.
UPDATE: Please note that, if your given URL (Line number: 26 ) is not having a secure connection means it uses http:// instead of https://, then your webpage won’t load up in the iPhone and will give you an error something like “App transport security has blocked a..”. So, to avoid this, we need to follow these steps:
- Go To Info.plist
- Click on + sign here
- Enter App Transport Security Settings
- Click on arrow sign and then + sign
- Now, write Allow Arbitrary Loads and change its value from NO to YES
If you’ve any doubts or need any further help, then do message me in the comments section below and I’ll try to respond you as soon as possible.
Thanks for your time and keep coding.. 👨💻