Один подход: добавить UIImageView
, охватывающий весь вид (или, по крайней мере, фрейм веб-вида). Реализация WKNavigationDelegate
. Когда вы получите уведомление о завершении навигации, удалите изображение.
class ViewController: UIViewController, WKNavigationDelegate {
var theWebView: WKWebView!
var splashImageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
theWebView = WKWebView()
splashImageView = UIImageView()
theWebView.translatesAutoresizingMaskIntoConstraints = false
splashImageView.translatesAutoresizingMaskIntoConstraints = false
// load splash image
if let img = UIImage(named: "mySplashImage") {
splashImageView.image = img
}
// add the web view and the splash image view
view.addSubview(theWebView)
view.addSubview(splashImageView)
NSLayoutConstraint.activate([
// constrain the web view to all 4 sides, with 20-pts "padding"
theWebView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 20.0),
theWebView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -20.0),
theWebView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 20.0),
theWebView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -20.0),
// constrain the splash image view to all 4 sides of the web view
splashImageView.topAnchor.constraint(equalTo: theWebView.topAnchor),
splashImageView.bottomAnchor.constraint(equalTo: theWebView.bottomAnchor),
splashImageView.leadingAnchor.constraint(equalTo: theWebView.leadingAnchor),
splashImageView.trailingAnchor.constraint(equalTo: theWebView.trailingAnchor),
])
// set navigation delegate
theWebView.navigationDelegate = self
// load a url
if let url = URL(string: "https://apple.com") {
theWebView.load(URLRequest(url: url))
}
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
// for debugging
print("Loaded")
// remove the splash image view
splashImageView.removeFromSuperview()
}
}
Примечания:
- это пример кода только для того, чтобы помочь вам - не считаться готовым к производству
- вы хотите обрабатывать ошибки (неверный URL и т. Д.)
- Вы, вероятно, хотите добавить спиннер (
UIActivityIndicatorView
) или индикатор выполнения, чтобы пользователь знал, что приложение ожидает загрузки веб-страницы.
Вот пример получения оценки прогресса загрузки, если вы хотите идти по этому маршруту: https://www.hackingwithswift.com/example-code/wkwebview/how-to-monitor-wkwebview-page-load-progress-using-key-value-observing