WebKit Error: This method should not be called on the main thread as it may lead to UI unresponsiveness

1k Views Asked by At

I'm currently facing an issue with threads in my iOS app. After testing, it seems that the problem is related to the WebKit integration.

Here is the relevant portion of the showTrailerViewController class:

class showTrailerViewController: UIViewController {

    private let webView: WKWebView = {
        let webView = WKWebView()
        webView.translatesAutoresizingMaskIntoConstraints = false
        return webView
    }()

    override func viewDidLoad() {
        view.addSubview(webView)
    }

    func configure(with model: ShowTrailerViewModel) {
        // Tasks that the user has initiated and requires immediate results
        DispatchQueue.global(qos: .userInitiated).async {
            // Perform network request on background thread
            guard let url = URL(string: "\(model.youtubeView.id.videoId)") else { return }
            let urlRequest = URLRequest(url: url)
            DispatchQueue.main.async {
                // Update UI on main thread
                self.showLabel.text = model.show
                self.overviewLabel.text = model.showOverview
                self.webView.load(urlRequest)
            }
        }
    }
}

Here is the protocol and its implementation that configure and run showTrailerViewController:

protocol CollectionViewTableViewCellDelegate: AnyObject {

    func CollectionViewTableViewCellDidTapCell(_ cell: CollectionTableViewCell , viewModel: ShowTrailerViewModel)

}

extension HomeViewController: CollectionViewTableViewCellDelegate {

    func CollectionViewTableViewCellDidTapCell(_ cell: CollectionTableViewCell, viewModel: ShowTrailerViewModel) {
        let vc = showTrailerViewController()
        vc.configure(with: viewModel)
        if self.navigationController?.viewControllers.contains(vc) == false {
            self.navigationController?.pushViewController(vc, animated: true)
        }
    }

}

Can someone help me understand why the WebKit integration is causing issues with threads and how to fix it? Thank you.

0

There are 0 best solutions below