ios 如何从URL获取HTML内容只使用URL会话,使其与watchOS和SwiftUI?

km0tfn4u  于 2023-03-05  发布在  iOS
关注(0)|答案(1)|浏览(142)

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

jdzmm42g1#

您可以使用URLSession获取HTML

guard
    let res = try? await URLSession.shared.data(from: url),
    let html = String(data: res.0, encoding: .utf8)
else { return }

相关问题