bounty将在3天后过期。回答此问题可获得+200的声望奖励。Bartłomiej Semańczyk正在寻找规范答案。
加载HTML的完整类如下所示:
import WebKit
class WebViewLoader: NSObject, WKNavigationDelegate {
private let webview = WKWebView()
private var url: URL?
private var completion: ((String)->Void)?
func setup(url: URL, completion: @escaping (String)->Void) {
self.url = url
self.completion = completion
webview.navigationDelegate = self
webview.load(URLRequest(url: url))
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
Timer.perform(withDelay: delay) { [weak self] in
webView.evaluateJavaScript("document.documentElement.outerHTML.toString()") { [weak self] html, error in
self?.completion?(html as? String ?? "")
}
}
}
}
我是这样使用它的:
let loader = WebViewLoader()
let url = URL(string: "https://www.apple.com/pl")!
loader.setup(url: url) { html in
//do anything with html
}
但这在Apple Watch上无法使用,因为watchOS上没有WebKit,有没有办法在没有WebKit的情况下获取HTML内容?
extension Timer {
class func perform(withDelay delay: Double, closure: @escaping ()->()) {
DispatchQueue.main.asyncAfter(deadline: .now() + delay as DispatchTime, execute: closure)
}
}
1条答案
按热度按时间jdzmm42g1#
您可以使用
URLSession
获取HTML