Search code examples
swiftwkwebview

WKWebView not displaying after successful load, only seeing black screen


I'm new to swift & am attempting to open a login page, login, use the WKNavigationDelegate to get the redirect uri and save the response. I was able to open the url using UIApplication.shared.open but attempting to hit the url using WKWebview, I am getting a loaded response but no view appears.

Am I not declarling the view correctly or is WKWebView not supposed to be used in that manner? This is the code i'm running, its building succesfully and responding that its 'loaded'. Any help would be be appreciated thanks.

import UIKit
import WebKit

class ViewController: UIViewController, WKUIDelegate, WKNavigationDelegate {
    
//    The webview
    var webViewObj: WKWebView!
    var webNav: WKNavigation!

//    this calls the dbhelper to create a db and a table
    let db = DBHelper()
    var list = [DBGrade]()
    
    override func loadView() {
        super.loadView()
        let webConfiguration = WKWebViewConfiguration()
        webViewObj = WKWebView(frame: .zero, configuration: webConfiguration)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        let url = URL(string: "https://www.hackingwithswift.com")
        let request = URLRequest(url: url!)
        
        webViewObj.navigationDelegate = self
        self.webViewObj.uiDelegate = self
        webViewObj.load(request)
    }
    
    
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        print("loaded")
    }

    func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
        if navigationAction.targetFrame == nil {
            webView.load(navigationAction.request)
        }
        return nil
    }
    
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        let hostStr = String(describing: navigationAction.request.url)
        
        let host = hostStr
        if host.range(of: "hackingwithswift.com") != nil {
            
            decisionHandler(.allow)
            print("did it")
            return
        }
        else{
            decisionHandler(.cancel)
        }
    }
}


Solution

  • So moving my delcaration of 'self.webViewObj.uiDelegate = self' & adding 'view = webViewObj' to the loadView() function worked & I'm able to see the webpage appear.