gpt4 book ai didi

swift - uiactivity 和 uiwebview 委托(delegate)

转载 作者:行者123 更新时间:2023-11-30 11:25:25 24 4
gpt4 key购买 nike

我的项目中有一个 uiactivity View 。我想在页面加载时开始动画,并在 webview 最终加载时停止并隐藏。这对我来说不起作用。

我尝试使用 UIWebViewDelegate,但它已被弃用。

class WebviewViewController: UIViewController {

@IBOutlet var webView: UIWebView!

@IBOutlet weak var activityIndicator: UIActivityIndicatorView!

let disposeBag = DisposeBag()
var specURL:String?

override func viewDidLoad() {
super.viewDidLoad()
configureUIActivityView()
_ = loadWebview()
.subscribe(onSuccess: { url in
DispatchQueue.main.async {
self.webView.loadRequest(URLRequest(url: url))
self.activityIndicator.stopAnimating()
self.activityIndicator.isHidden = true
}
})
}

func loadWebview() -> Single<URL> {
return Single<URL>.create { single in
guard let url = URL(string: self.specURL!.trimmingCharacters(in: .whitespacesAndNewlines)) else {
assertionFailure("no view available")
//single(.error(NetworkError.noImage))
return Disposables.create {}
}
single(.success(url))
return Disposables.create {}
}
}
}

最佳答案

最好使用 WKWebView 来实现,因为正如您提到的 UIWebViewDelegate 已被弃用。

这里是一个使用 KVO 监控 WKWebView 加载状态的简单示例。

import WebKit

class ViewController: UIViewController, WKUIDelegate {

private var webView: WKWebView!

override func loadView() {
let webConfiguration = WKWebViewConfiguration()
webView = WKWebView(frame: .zero, configuration: webConfiguration)
webView.uiDelegate = self
view = webView
webView.addObserver(self, forKeyPath: "loading", options: .new, context: nil)
}

override func viewDidLoad() {
super.viewDidLoad()
let myURL = URL(string: "http://www.apple.com")
let myRequest = URLRequest(url: myURL!)
webView.load(myRequest)
}

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
guard let keyPath = keyPath, let change = change else { return }
switch keyPath {
case "loading":
if let loading = change[.newKey] as? Bool {
print("Is webview loading: \(loading)")
}
default:
break
}
}

deinit {
webView.removeObserver(self, forKeyPath: "loading")
}
}

关于swift - uiactivity 和 uiwebview 委托(delegate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50787401/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com