WKWebView and WKWebViewDelegate Method in Swift
WKWebView
The UIWebView which is part of UIKit. UIWebView class has been around iOS 2.0 and it is most successfully browser to display HTML content inside the apps. and it's very simple to open URL in your apps using UIWebView.
Now, After iOS 8 and Later, Apple introduces new class WKWebView in WebKit. WKWebView is faster to load a webpage and more efficiently rather than UIWebView. WKWebView runs as Separate process to the apps. Don't have memory overhead in apps.
Now, Follow these steps to load your URL in WKWebView in Swift.
Step - 1 : Open the Xcode, Create a new project and select Single View Application template as below.
Step - 2 : After selecting, enter the product name as "WebView_WebKit". Set your Organization name and Organization identifier Then press the next and create the new project.
Step - 3 : Select Main.storyboard file and search WKWebView from Object Library and Drag and Drop in View. also set constraints of WKWebView.
Step - 4 : Select WKWebView and Add to IBOutlet connection in ViewController.swift file.
After connecting with IBOutlet, there is created an instance of WKWebView.
@IBOutlet weak var wkWebview: WKWebView!
Step - 5 :In ViewController.swift file, import the WebKit framework.
import WebKit
Step - 6 :Adding the delegate WKNavigationDelegate in ViewController.swift file. And Take the default URL which wants to load in WKWebView. Define code in ViewDidLoad.
class ViewController: UIViewController,WKNavigationDelegate
{
override func viewDidLoad()
{
super.viewDidLoad()
let myBlog = "https://www.apple.com"
let url = NSURL(string: myBlog)
let request = NSURLRequest(url: url! as URL)
wkWebview.navigationDelegate = self
wkWebview.load(request as URLRequest)
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error)
{
print(error.localizedDescription)
}
func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!)
{
// UIApplication.shared.isNetworkActivityIndicatorVisible = true
print("Strat to load")
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!)
{
// UIApplication.shared.isNetworkActivityIndicatorVisible = false
print("finish to load")
}
}
You can easily download demo code by clicking here.
Contact us; If you have any query regarding iOS Application / Apple Watch Application / iMessage Extension / Today’s Extension OR you have your own application idea let us know. We have expert iOS team for your help.