Created
August 4, 2019 02:57
-
-
Save d-date/c3e705bc87f85dc6e7be347c84fec011 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
import WebKit | |
class WKWebViewController: UIViewController { | |
var request: URLRequest? | |
weak var uiDelegate: WKUIDelegate? | |
weak var navigationDelegate: WKNavigationDelegate? | |
lazy var webView: WKWebView = { | |
let config = WKWebViewConfiguration() | |
let webView = WKWebView(frame: .zero, configuration: config) | |
webView.uiDelegate = self.uiDelegate | |
webView.navigationDelegate = self.navigationDelegate | |
return webView | |
}() | |
private lazy var heightConstraint: NSLayoutConstraint = webView.heightAnchor.constraint(equalToConstant: 0) | |
init(request: URLRequest? = nil, uiDelegate: WKUIDelegate? = nil, navigationDelegate: WKNavigationDelegate? = nil) { | |
self.request = request | |
super.init(nibName: nil, bundle: nil) | |
self.uiDelegate = uiDelegate ?? self | |
self.navigationDelegate = navigationDelegate ?? self | |
} | |
required init?(coder: NSCoder) { | |
fatalError("init(coder:) has not been implemented") | |
} | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
view.addSubview(webView, constraints: .allEdges()) | |
heightConstraint.isActive = true | |
if let request = self.request { | |
webView.load(request) | |
} | |
} | |
} | |
extension WKWebViewController: WKNavigationDelegate { | |
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { | |
webView.evaluateJavaScript("document.readyState", completionHandler: { [weak self] (complete, error) in | |
if complete != nil { | |
self?.heightConstraint.constant = webView.scrollView.contentSize.height | |
} | |
}) | |
} | |
} | |
extension WKWebViewController: WKUIDelegate { | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment