WKNavigationDelegate method is not called - ios

I'm currently writing a web view application using WKWebView, which should show a custom error page when there is no internet connection while loading a page. I've tried to handle this by calling a method of WKNavigationDelegate, but it's never called. I'm new to Swift and I already tried some solutions I've found here on stackoverflow, but none of them worked for me. Am I doing something wrong?
import UIKit
import WebKit
class ViewController: UIViewController, WKUIDelegate, WKNavigationDelegate {
var webView: WKWebView!
override func 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://google.com")
let myRequest = URLRequest(url: myURL!)
webView.load(myRequest)
}
func webView(webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: NSError)
{
let url = Bundle.main.url(forResource: "no_connection", withExtension: "html")!
webView.loadFileURL(url, allowingReadAccessTo: url)
let request = URLRequest(url: url)
webView.load(request)
}
}

The signature func(webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: NSError) { } is incorrect.
Try instead func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) { }.
There should be even a warning, telling you that with the first signature you aren't using a delegate function:

Related

switch view if the Webview can't loading the URL?

I have 2 views on my screen first is the Webview and the second is a static view "errorView" with the error message "set to hidden". I am trying to load the errorView if we have an error loading website to Webview.
#objc private func loadURL() {
guard let url = URL(string: "https://www.hackingwi") else {
self.errroLoadingWebView.isHidden = false
return
}
webView?.load(URLRequest(url: url))
webView?.allowsBackForwardNavigationGestures = true
}
You can use WKNavigationDelegate.
set delegate
webView.uiDelegate = self
webView.navigationDelegate = self
class StaticWebPageVC: WKNavigationDelegate, WKUIDelegate {
func webView(_: WKWebView, didFinish _: WKNavigation!) {
// Web view loaded
}
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
// Show error view
}
func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
// Show error view
}
}

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)
}
}

wkwebview won't display a youtube video in an iframe

I am trying to use a WKWebView under iOS 9 and one of the pages happens to have a youtube video in an iframe. The video does not display. The same video works in Safari so doesn't seem to be an iOS issue, I assume I am missing a configuration option in the view. A sample URL is http://www.w3schools.com/html/tryit.asp?filename=tryhtml_youtubeiframe.
import UIKit
import WebKit
class ViewController: UIViewController, WKNavigationDelegate
{
var webView : WKWebView!
override func viewDidLoad()
{
super.viewDidLoad()
let webviewConfiguration = WKWebViewConfiguration()
webviewConfiguration.allowsInlineMediaPlayback = true
webviewConfiguration.preferences.javaScriptCanOpenWindowsAutomatically = true
webviewConfiguration.allowsAirPlayForMediaPlayback = true
webviewConfiguration.allowsPictureInPictureMediaPlayback = true
webviewConfiguration.requiresUserActionForMediaPlayback = false
webView = WKWebView(frame: self.view.bounds,
configuration: webviewConfiguration)
webView.navigationDelegate = self
self.view = webView
let url = NSURL(string: "http://www.w3schools.com/html/tryit.asp?filename=tryhtml_youtubeiframe")
let req = NSURLRequest(URL: url!)
self.webView!.loadRequest(req)
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
}
func webView(webView: WKWebView,
didFailNavigation navigation: WKNavigation!,
withError error: NSError)
{
print("didFailNavigation \(error)")
}
func webView(webView: WKWebView,
didFailProvisionalNavigation navigation: WKNavigation!,
withError error: NSError)
{
print("didFailProvisionalNavigation \(error)")
}
}
Go to Projects info.plist file
Added a Key called NSAppTransportSecurity as a Dictionary.
Added a Subkey called NSAllowsArbitraryLoads as Boolean and set its value to YES. It works.

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")
}

Activity Indicator won't stop spinning after WKWebView load finish

I am very new to Swift and iOS development so thank you so much in advance for helping me!
I have tried every example online and every page on this site and I cannot get my Activity Indicator to stop being displayed once the page completes loading in my WKWebview.
Any assistance would be so appreciated! Thank you!
import UIKit
import WebKit
class FirstViewController: UIViewController, WKUIDelegate, WKNavigationDelegate {
#IBOutlet var webView: WKWebView!
#IBOutlet var activityIndicator: UIActivityIndicatorView!
override func viewDidLoad() {
super.viewDidLoad()
webView.uiDelegate = self
activityIndicator.startAnimating()
activityIndicator.isHidden = true
activityIndicator.hidesWhenStopped = true
let url = Bundle.main.url(forResource: "Web/bulk_material_table", withExtension: "html")!
webView.loadFileURL(url, allowingReadAccessTo: url)
let request = URLRequest(url: url)
self.webView.load(request)
}
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)
}
}
Just replace
webView.uiDelegate = self
with
webView.navigationDelegate = self
And it will work because
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
showActivityIndicator(show: false)
}
is WKNavigationDelegate's delegate method.

Resources