加载WKWebview时为零

问题描述 投票:0回答:1

我使用Xcode 11.0和Swift 5.1。并且我使用WKWebview加载网站,并且第一次加载时没有问题。但第二次加载问题。

文件名:TabBarController.swift

import UIKit

class TabBarController: UITabBarController, UITabBarControllerDelegate {
    var isSelected = true

    override func viewDidLoad() {
        super.viewDidLoad()
        self.delegate = self
    }
    override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
        let tabBarIndex = tabBar.items?.firstIndex(of: item)


        if isSelected == true && tabBarIndex == 0{
            let vc = ViewController()
            print("Go to amazon page")
            vc.handleReload()
        }
        else{
            if tabBarIndex == 0{
                isSelected = true
                print("home!")
            }
            else{
                isSelected = false
                print("setting!")
            }
        }
    }
}

文件名:ViewController.swift

import UIKit
import WebKit

class ViewController: UIViewController {

    var webView: WKWebView!

    override func loadView() {
        let webConfiguration = WKWebViewConfiguration()
        webView = WKWebView(frame: .zero, configuration: webConfiguration)
        webView.uiDelegate = self
        view = webView
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        let url: URL = URL(string: "https://google.com")!
        self.webView.load(URLRequest(url: url))
    }
}

//MARK: - function
extension ViewController: WKUIDelegate, WKNavigationDelegate{
     func handleReload() {
        let url: URL = URL(string: "https://www.amazon.com")!
        self.webView.load(URLRequest(url: url))
    }

     func cacheReset() {
        let DataTypes = NSSet(array: [WKWebsiteDataTypeDiskCache, WKWebsiteDataTypeMemoryCache])
        let date = NSDate(timeIntervalSince1970: 0)
        WKWebsiteDataStore.default().removeData(ofTypes: DataTypes as! Set<String>, modifiedSince: date as Date){
            print("Cache Reset End")
        }

    }
}

[self.webView.load(URLRequest(url: url))中的func handleReload()处发生错误,这是错误日志:Thread 1: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value我不明白为什么WKWebview变为零:(我做错了吗?

ios swift
1个回答
0
投票

您无需再创建ViewController,因为您已经作为子项添加到TabBarController。您可以按以下方式获取该实例,然后在同一实例上调用require方法,而不用创建一个新实例。

if isSelected == true && tabBarIndex == 0 {
    if let viewController = self.children.first(where: { $0 is ViewController }) {
        viewController.handleReload()
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.