how do I get WKWebView to work in swift and for an macOS App [duplicate]

[亡魂溺海] 提交于 2019-12-08 19:13:57

问题


before this get's shot down for being a duplicate, it isn't. Pretty much every question on WKWebView here is about WKWebView in iOS Apps, not macOS Apps, with the difference being pretty much just the UIViewController interface being implemented instead of the NSViewController interface in macOS.

The example code in Apple's Documentation as well as the Controller code, that can be found online doesn't work. Altough it does compile without a problem the webview stays inactive.

Is there something that I just didn't see or is this a bug in WKWebView ?
I even copied some code from tutorials showing how to do this for iOS and just changed UIViewController to NSViewController (since that was the ONLY difference), yet it didn't work.

The following code in ViewController.swift does not work. It also doesn't work if it's
class ViewController: NSViewController, WKUIDelegate

import Cocoa;
import WebKit;
class ViewController: NSViewController {
    @IBOutlet weak var webView: WKWebView!
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        let url=URL(string: "http://safetec-cam.biz/images/webcam_extern/bad-nauheim_bahnhof_west.jpg");
        webView.load(URLRequest(url: url!));
    }
}

it also doesn't work if it's done like this with the UIViewController exchanged for NSViewController image from https://developer.apple.com/documentation/webkit/wkwebview


回答1:


I recommend you to start from the scratch:

Set Your URL to be loaded:

let myURLString = "https:yourWebLink"
let url = NSURL(string: myURLString)
let request = NSURLRequest(URL: url!)  

Init and load request in webview:

 let webView = WKWebView(frame: self.view.frame)
 webView.navigationDelegate = self
 webView.loadRequest(request)

Implement WKNavigationDelegate to trace your page Load/Error:

extension ViewController: WKNavigationDelegate {

    func webView(webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        print("Strat to load")
    }

    func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) {
        print("finish to load")
    }

    func webView(webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: NSError) {
            print(error.localizedDescription)
        }
  }

For further reference check: https://iosdevcenters.blogspot.com/2016/05/creating-simple-browser-with-wkwebview.html



来源:https://stackoverflow.com/questions/44465974/how-do-i-get-wkwebview-to-work-in-swift-and-for-an-macos-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!