How to add Activity Indicator to WKWebView (Swift 3) - ios

I have a wkwebview in my app, and I want to add an activity indicator to it. I want it to where it appears when the webview is loading and disappears whenever it is finished loading, it disappears. Can you give me some code to do this? Here's my code right now:
#IBOutlet weak var Activity: UIActivityIndicatorView!
var webView : WKWebView!
#IBOutlet var containerView: UIView? = nil
override func viewDidLoad() {
super.viewDidLoad()
guard let url = URL(string: "http://ifunnyvlogger.wixsite.com/ifunnyvlogger/app-twitter") else { return }
webView = WKWebView(frame: self.view.frame)
webView.translatesAutoresizingMaskIntoConstraints = false
webView.isUserInteractionEnabled = true
webView.navigationDelegate = self
self.view.addSubview(self.webView)
let request = URLRequest(url: url)
webView.load(request)
}
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: #escaping (WKNavigationActionPolicy) -> Void) {
// Check if a link was clicked
if navigationAction.navigationType == .linkActivated {
// Verify the url
guard let url = navigationAction.request.url else { return }
let shared = UIApplication.shared
// Check if opening in Safari is allowd
if shared.canOpenURL(url) {
// Ask the user if they would like to open link in Safari
let alert = UIAlertController(title: "Do you want to open Safari?", message: nil, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Yes", style: .default, handler: { (alert: UIAlertAction) -> Void in
// User wants to open in Safari
shared.open(url, options: [:], completionHandler: nil)
}))
alert.addAction(UIAlertAction(title: "Opps, no.", style: .cancel, handler: nil))
present(alert, animated: true, completion: nil)
}
decisionHandler(.cancel)
}
decisionHandler(.allow)
}
func webViewDidStartLoad(_ : WKWebView) {
Activity.startAnimating()
}
func webViewDidFinishLoad(_ : WKWebView) {
Activity.startAnimating()
}
I'm creating an IOS app using xcode 8 and swift 3

Please, below code which is working fine.
#IBOutlet weak var Activity: UIActivityIndicatorView!
var webView : WKWebView!
#IBOutlet var containerView: UIView? = nil
override func viewDidLoad() {
super.viewDidLoad()
guard let url = URL(string: "http://www.facebook.com") else { return }
webView = WKWebView(frame: self.view.frame)
webView.translatesAutoresizingMaskIntoConstraints = false
webView.isUserInteractionEnabled = true
self.view.addSubview(self.webView)
let request = URLRequest(url: url)
webView.load(request)
// add activity
self.webView.addSubview(self.Activity)
self.Activity.startAnimating()
self.webView.navigationDelegate = self
self.Activity.hidesWhenStopped = true
}
Implement below these two delegate method:
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
Activity.stopAnimating()
}
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
Activity.stopAnimating()
}
Let me know if it is not working.

import UIKit
import WebKit
class ViewController: UIViewController, WKNavigationDelegate, WKUIDelegate {
var webView: WKWebView!
var activityIndicator: UIActivityIndicatorView!
override func viewDidLoad() {
webView = WKWebView(frame: CGRect.zero)
webView.navigationDelegate = self
webView.uiDelegate = self
view.addSubview(webView)
activityIndicator = UIActivityIndicatorView()
activityIndicator.center = self.view.center
activityIndicator.hidesWhenStopped = true
activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.gray
view.addSubview(activityIndicator)
webView.load(URLRequest(url: URL(string: "http://google.com")!))
}
func showActivityIndicator(show: Bool) {
if show {
activityIndicator.startAnimating()
} else {
activityIndicator.stopAnimating()
}
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
showActivityIndicator(show: false)
}
func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
showActivityIndicator(show: true)
}
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
showActivityIndicator(show: false)
}
}

Swift 5 Version
The concept is simple enough to be ported to earlier swift versions.
This is a class we would use as a parent class anywhere we want a webview.
import UIKit
import WebKit
class CustomWebViewController: UIViewController, WKNavigationDelegate {
var activityIndicator: UIActivityIndicatorView!
override func viewDidLoad() {
super.viewDidLoad()
activityIndicator = UIActivityIndicatorView()
activityIndicator.center = self.view.center
activityIndicator.hidesWhenStopped = true
activityIndicator.style = .gray
activityIndicator.isHidden = true
view.addSubview(activityIndicator)
}
func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
activityIndicator.isHidden = false
activityIndicator.startAnimating()
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
activityIndicator.stopAnimating()
activityIndicator.isHidden = true
}
}
If we have a UIViewController with a webview, we can just inherit from CustomWebViewController and it will take care of the rest for us. Remember to connect the webview IBOutlet.
import UIKit
import WebKit
class FirstViewController: CustomWebViewController {
#IBOutlet var webView: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
webView.navigationDelegate = self
let url = URL(string: "https://google.com")
webView.load(URLRequest(url: url!))
}
}

In viewDidLoad you need to add the activityIndicator as a subView just as you did for your webView. Since it's an outlet, make sure the activityIndicator sits on top of your webView and you should be good to go. You also want to set activity.hidden to true when the webView stops loading.
It's also a good rule of thumb to lower case your 'Activity' outlet.
override func viewDidLoad() {
super.viewDidLoad()
self.view.addSubview(self.Activity)
guard let url = URL(string: "http://ifunnyvlogger.wixsite.com/ifunnyvlogger/app-twitter") else { return }
webView = WKWebView(frame: self.view.frame)
webView.translatesAutoresizingMaskIntoConstraints = false
webView.isUserInteractionEnabled = true
webView.navigationDelegate = self
self.view.addSubview(self.webView)
let request = URLRequest(url: url)
webView.load(request)
You also call activity.startAnimating in webViewDidFinishLoad(). Make sure you call activity.stopAnimating() when the webView finishes loading. Happy coding!
func webViewDidFinishLoad(_ : WKWebView) {
Activity.stopAnimating()
Activity.hidden = true
}

import UIKit
import WebKit
class ViewController: UIViewController, WKNavigationDelegate, WKUIDelegate {
var webView: WKWebView!
var activityIndicator: UIActivityIndicatorView!
override func viewDidLoad() {
webView = WKWebView(frame: CGRect.zero)
webView.navigationDelegate = self;
webView.uiDelegate = self
activityIndicator = UIActivityIndicatorView()
activityIndicator.hidesWhenStopped = true
activityIndicator.center = self.view.center
activityIndicator.style = UIActivityIndicatorView.Style.large
webView.addSubview(activityIndicator)
view = webView
let load_url = URL(string: "https://google.com/")!
webView.load(URLRequest(url: load_url))
activityIndicator.startAnimating()
let refresh = UIBarButtonItem(barButtonSystemItem: .refresh, target: webView, action: #selector(webView.reload))
toolbarItems = [refresh]
navigationController?.isToolbarHidden = false
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
title = webView.title
activityIndicator.stopAnimating()
}
func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
activityIndicator.startAnimating()
}
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
activityIndicator.stopAnimating()
}
}

Please try the below code its working fine for me and please let me know if anything is wrong in it thanks in advance.
import UIKit
import WebKit
class WebViewController: UIViewController, WKUIDelegate, WKNavigationDelegate {
#IBOutlet weak var contentView: UIView!
#IBOutlet weak var activityIndicatorView: UIActivityIndicatorView!
override func viewDidLoad() {
super.viewDidLoad()
setupView()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.setupWebView()
self.loadData()
}
fileprivate func setupView() {
self.contentView.isHidden = true
self.activityIndicatorView.startAnimating()
}
fileprivate func setupWebView() {
let webConfiguration = WKWebViewConfiguration()
webView = WKWebView(frame: contentView.bounds, configuration: webConfiguration)
webView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
self.contentView.addSubview(webView)
self.webView.allowsBackForwardNavigationGestures = true
webView.uiDelegate = self
webView.navigationDelegate = self
}
fileprivate func loadData() {
if let url = URL(string: "http://google.com") {
/// For loading PDF content
if contentType == .pdf {
if let data = try? Data(contentsOf: url) {
self.webView.load(data, mimeType: "application/pdf", characterEncodingName: "", baseURL: url)
}
} else {
let request = URLRequest(url: url)
webView.load(request)
}
}
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
activityIndicatorView.stopAnimating()
self.contentView.isHidden = false
}
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
activityIndicatorView.stopAnimating()
}
}

Related

Why my WKWebview inside my UIScrollView is not displayed?

I need to add a WKWebview to load web content, inside the content view of UIScrollView.
I'm using the Apple code to load a web page, my outlet viewForWebview is linked correctly, and didFinish is called.
class ViewController: UIViewController, WKUIDelegate, WKNavigationDelegate {
var webView: WKWebView!
#IBOutlet var viewForWebview: UIView!
override func loadView() {
super.loadView()
let myConfiguration = WKWebViewConfiguration()
webView = WKWebView(frame: .zero, configuration: myConfiguration)
webView.uiDelegate = self
webView.navigationDelegate = self
viewForWebview = webView
}
override func viewDidLoad() {
super.viewDidLoad()
let url = URL(string: "https://www.google.com.au")
let request = URLRequest(url: url!)
webView.load(request)
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
print("Finished navigating to url \(String(describing: webView.url))")
}
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
print(error)
}
}
But my the WKWebview is blank:
Just to test, I tried to display the WKWebview directly inside the content view of the scroll view, and it works.
Why is it not working as subview of the content?
Don't override loadView for such actions , you need
class ViewController: UIViewController, WKUIDelegate, WKNavigationDelegate {
var webView: WKWebView!
#IBOutlet var viewForWebview: UIView!
override func viewDidLoad() {
super.viewDidLoad()
let myConfiguration = WKWebViewConfiguration()
webView = WKWebView(frame:.zero, configuration: myConfiguration)
webView.uiDelegate = self
webView.navigationDelegate = self
viewForWebview.addSubview(webView)
webView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
webView.topAnchor.constraint(equalTo: viewForWebview.topAnchor),
webView.bottomAnchor.constraint(equalTo: viewForWebview.bottomAnchor),
webView.leadingAnchor.constraint(equalTo: viewForWebview.leadingAnchor),
webView.trailingAnchor.constraint(equalTo: viewForWebview.trailingAnchor)
])
let url = URL(string: "https://www.apple.com")
let request = URLRequest(url: url!)
webView.load(request)
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
print("Finished navigating to url \(String(describing: webView.url))")
}
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
print(error)
}
}

create activity indicator when navigate in webView using webkit in swift 4

I want to create a wkwebview in my iOS app, and I want to add an activity indicator to it. I want when we click all the button or part in the webview, it will appear the activity indicator. Can you give me some code to do this? Here's my code right now. It only show the indicator when start load the website but when we click at the process, the indicator not appear.
import UIKit
import WebKit
class ViewController: UIViewController,WKNavigationDelegate,UIWebViewDelegate {
#IBOutlet weak var activityIndicator: UIActivityIndicatorView!
#IBOutlet weak var webView: WKWebView!
#IBOutlet var containerView: UIView? = nil
override func viewDidLoad() {
super.viewDidLoad()
self.view.addSubview(self.activityIndicator)
self.view.addSubview(self.webView)
let url:URL = URL(string : "https://www.facebook.com/")!
let urlRequest : URLRequest = URLRequest(url: url)
webView.load(urlRequest)
//activity indicator
self.webView.addSubview(self.activityIndicator)
self.activityIndicator.startAnimating()
self.webView.navigationDelegate = self
self.activityIndicator.hidesWhenStopped = true
//refresh
webView.scrollView.bounces = true
let refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action: #selector(ViewController.refreshWebView), for: UIControlEvents.valueChanged)
webView.scrollView.addSubview(refreshControl)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear( animated )
let url:URL = URL(string : "https://www.facebook.com/")!
let urlRequest : URLRequest = URLRequest(url: url)
webView.load(urlRequest)
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
activityIndicator.stopAnimating()
}
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
activityIndicator.stopAnimating()
}
#objc func refreshWebView(sender: UIRefreshControl) {
print("refersh")
sender.endRefreshing()
}
}
Below code will help to add activity indicator in Navigation Bar. So no need to create any subviews. This works with Swift 4.
import Foundation
import UIKit
import WebKit
class ContactVC: UIViewController, WKNavigationDelegate {
var webView: WKWebView!
var activityIndicator: UIActivityIndicatorView!
override func loadView() {
webView = WKWebView()
webView.navigationDelegate = self
view = webView
activityIndicator = UIActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.gray
activityIndicator.hidesWhenStopped = true
let barButton = UIBarButtonItem(customView: activityIndicator)
self.navigationItem.setRightBarButton(barButton, animated: true)
}
override func viewDidLoad() {
super.viewDidLoad()
let url = URL(string: "https://www.facebook.com/")!
webView.load(URLRequest(url: url))
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func showActivityIndicator(show: Bool) {
if show {
// Start the loading animation
activityIndicator.startAnimating()
} else {
// Stop the loading animation
activityIndicator.stopAnimating()
}
}
//MARK:- WKNavigationDelegate
func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
print("Start to load")
showActivityIndicator(show: true)
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
print("Finish to load")
title = webView.title
showActivityIndicator(show: false)
}
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
print(error.localizedDescription)
showActivityIndicator(show: false)
}
func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
print(error.localizedDescription)
showActivityIndicator(show: false)
}
}
Implement didStartProvisionalNavigation delegate function.
func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
activityIndicator.startAnimating()
}

Some WKWebView links not clickable

I am having a challenge with a WKWebView-based iOS application: some of the links on the page are not clickable. When I try them with a Safari view controller, they work. Please can anyone help me?
This is my source code:
import UIKit
import WebKit
class ViewController: UIViewController, WKUIDelegate, WKNavigationDelegate {
var webView: WKWebView! //declare the webview has to be optional
var activityIndicator: UIActivityIndicatorView!
override func loadView() {
super.loadView()
let webConfiguration = WKWebViewConfiguration()
webView = WKWebView(frame: .zero, configuration: webConfiguration)
webView.uiDelegate = self
webView.navigationDelegate = self
view = webView
}
override func viewDidLoad() {
super.viewDidLoad()
let myURL = URL(string: "https://stolenandfound.com/")
let myRequest = URLRequest(url: myURL!)
webView.load(myRequest)
activityIndicator = UIActivityIndicatorView() //declare the progress indicator
activityIndicator.frame = CGRect(x: 0, y: 0, width: 50, height: 50)
self.activityIndicator.center = CGPoint(x:self.view.bounds.size.width/2.0,y: self.view.bounds.size.height/2.0);
activityIndicator.autoresizingMask = (UIViewAutoresizing(rawValue: UIViewAutoresizing.RawValue(UInt8(UIViewAutoresizing.flexibleRightMargin.rawValue) | UInt8(UIViewAutoresizing.flexibleLeftMargin.rawValue) | UInt8(UIViewAutoresizing.flexibleBottomMargin.rawValue) | UInt8(UIViewAutoresizing.flexibleTopMargin.rawValue))))
//activityIndicator.center = CGPoint(x: UIScreen.main.bounds.size.width/2, y: UIScreen.main.bounds.size.height/2)
activityIndicator.hidesWhenStopped = true
activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.whiteLarge
activityIndicator.color = UIColor.darkGray
self.view.addSubview(activityIndicator)
}
func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
activityIndicator.startAnimating()
}
func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
print("it is an error")
activityIndicator.stopAnimating()
let alert = UIAlertController(title: "Network Error", message: "You have no internet coonection", preferredStyle: .alert)
let restartAction = UIAlertAction(title: "Reload page", style: .default, handler: { (UIAlertAction) in
self.viewDidLoad()
})
alert.addAction(restartAction)
present(alert, animated: true, completion: nil)
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
activityIndicator.stopAnimating()
}
#IBAction func backButton(_ sender: UIBarButtonItem) {
webView.goBack()
}
#IBAction func refreshButton(_ sender: UIBarButtonItem) {
webView.reload()
}
}
If the links open in a new tab in Safari, you will have to implement the WKUIDelegate function func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? and handle the request there. At that point you can load the request in the existing webView or create a new webView or open it in Safari.
func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
guard let theURL = navigationAction.request.url else {
return nil
}
if loadInCurrentWebview{
_ = webView.load(navigationAction.request) //loads the link in the current webView
} else if loadInNewWebview{
return WKWebView()
}else {
//loads in safari
if #available(iOS 10.0, *) {
UIApplication.shared.open(theURL, options: [:], completionHandler: nil)
} else {
UIApplication.shared.openURL(theURL)
}
}
return nil
}

Displaying activity indicator on WKWebView using swift

I am working on the following code and trying to show an activity indicator in the view whilst the page is loading..
I tried to implement the WKNavigationDelegate methods but I am failing as nothing shows.
Any suggestions on how to fix this?
I am not setting the SupportWebView view delegate anywhere but I wouldn't know how to do it in swift..
import UIKit
import WebKit
class SupportWebView: UIViewController, WKNavigationDelegate {
#IBOutlet var containerView : UIView? = nil
var webView: WKWebView?
override func loadView() {
super.loadView()
self.webView = WKWebView()
self.view = self.webView
}
override func viewDidLoad() {
super.viewDidLoad()
var dataManager = DataManager.sharedDataManager()
var url = dataManager.myValidURL
var req = NSURLRequest(URL:url!)
self.webView!.loadRequest(req)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func webView(webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
}
func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) {
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
}
}
As commented, you forgot to set the webView delegate:
override func loadView() {
super.loadView()
self.webView = WKWebView()
self.webView.navigationDelegate = self
self.view = self.webView
}
You should use the delegate methods for all other purposes, but key path monitoring works fine for this one purpose.
Here is a Swift 4 implementation that works fine.
// Somewhere in your view controller
private var loadingObservation: NSKeyValueObservation?
private lazy var loadingIndicator: UIActivityIndicatorView = {
let spinner = UIActivityIndicatorView()
spinner.translatesAutoresizingMaskIntoConstraints = false
spinner.color = .black
return spinner
}()
override func viewDidLoad() {
super.viewDidLoad()
// Setup...
loadingObservation = webView.observe(\.isLoading, options: [.new, .old]) { [weak self] (_, change) in
guard let strongSelf = self else { return }
// this is fine
let new = change.newValue!
let old = change.oldValue!
if new && !old {
strongSelf.view.addSubview(strongSelf.loadingIndicator)
strongSelf.loadingIndicator.startAnimating()
NSLayoutConstraint.activate([strongSelf.loadingIndicator.centerXAnchor.constraint(equalTo: strongSelf.view.centerXAnchor),
strongSelf.loadingIndicator.centerYAnchor.constraint(equalTo: strongSelf.view.centerYAnchor)])
strongSelf.view.bringSubview(toFront: strongSelf.loadingIndicator)
}
else if !new && old {
strongSelf.loadingIndicator.stopAnimating()
strongSelf.loadingIndicator.removeFromSuperview()
}
}
}
Please, below code which is working fine[Swift 4.2].
#IBOutlet weak var wv: WKWebView!
#IBOutlet weak var activityIndicator: UIActivityIndicatorView!
override func viewDidLoad() {
super.viewDidLoad()
loadYoutube(videoID: "KqNS7uAvOxk")
}
Now load Youtube Video
func loadYoutube(videoID:String) {
guard let youtubeURL = URL(string: "https://www.youtube.com/embed/\(videoID)")
else { return }
wv.load( URLRequest(url: youtubeURL) )
wv.navigationDelegate = self
}
Implement below this function:
func showActivityIndicator(show: Bool) {
if show {
activityIndicator.startAnimating()
} else {
activityIndicator.stopAnimating()
}
}
Implement below these three delegate method:
func webView(_ webView: WKWebView, didFinish navigation:
WKNavigation!) {
showActivityIndicator(show: false)
}
func webView(_ webView: WKWebView, didStartProvisionalNavigation
navigation: WKNavigation!) {
showActivityIndicator(show: true)
}
func webView(_ webView: WKWebView, didFail navigation:
WKNavigation!, withError error: Error) {
showActivityIndicator(show: false)
}
Let me know if it is not working.

WKWebView Content loaded function never get called

i try to get a function called after my Content inside WKWebView is fully loaded. I found the "didFinishNavigation" function at the Apple Swift WKNavigation Documentation.
func webView(webView: WKWebView!, didFinishNavigation navigation: WKNavigation!) {
println("WebView content loaded.")
}
But the function never get called.
import UIKit
import WebKit
class ViewController: UIViewController WKNavigationDelegate {
override func loadView() {
super.loadView()
self.webView = WKWebView(frame:self.containerView.frame, configuration: WKWebViewConfiguration())
self.containerView.addSubview(webView!)
self.containerView.clipsToBounds = true
}
override func viewDidLoad() {
super.viewDidLoad()
var url = NSURL(string:"http://google.com/")
var req = NSURLRequest(URL:url)
self.webView!.loadRequest(req)
}
func webView(webView: WKWebView!, didFinishNavigation navigation: WKNavigation!) {
println("WebView content loaded.")
}
}
You are not setting the navigationDelegate. Set it and it should be fine.
class ViewController: UIViewController, WKNavigationDelegate {
override func viewDidLoad() {
super.viewDidLoad()
let noLayoutFormatOptions = NSLayoutFormatOptions(rawValue: 0)
let webView = WKWebView(frame: CGRectZero, configuration: WKWebViewConfiguration())
webView.setTranslatesAutoresizingMaskIntoConstraints(false)
webView.navigationDelegate = self
view.addSubview(webView)
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[webView]|", options: noLayoutFormatOptions, metrics: nil, views: ["webView": webView]))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[webView]|", options: noLayoutFormatOptions, metrics: nil, views: ["webView": webView]))
let url = NSURL(string: "http://google.com")
let request = NSURLRequest(URL: url)
webView.loadRequest(request)
}
func webView(webView: WKWebView!, didFinishNavigation navigation: WKNavigation!) {
print("Finished navigating to url \(webView.url)");
}
}
And here is a bit better version with Swift 3.
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let configuration = WKWebViewConfiguration()
let webView = WKWebView(frame: .zero, configuration: configuration)
webView.translatesAutoresizingMaskIntoConstraints = false
webView.navigationDelegate = self
view.addSubview(webView)
[webView.topAnchor.constraint(equalTo: view.topAnchor),
webView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
webView.leftAnchor.constraint(equalTo: view.leftAnchor),
webView.rightAnchor.constraint(equalTo: view.rightAnchor)].forEach { anchor in
anchor.isActive = true
}
if let url = URL(string: "https://google.com/search?q=westworld") {
webView.load(URLRequest(url: url))
}
}
}
extension ViewController: WKNavigationDelegate {
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
print("Finished navigating to url \(webView.url)")
}
}
I made a simple mistake for not adding a subview to my View
view.addSubview(webView)
I have created a webView programmatically, here is the complete code
1.. import WebKit
2.. func viewDidLoad()
let request = URLRequest(url: url)
let webView = WKWebView(frame: view.frame)
view.addSubview(webView)
webView.navigationDelegate = self
webView.load(request)
3.. Implement extension for delegate methods
// MARK: WKWebView
extension ViewController: WKNavigationDelegate {
func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
print("Start Request")
}
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
print("Failed Request")
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
print("Finished Request")
}

Resources