How to initialise a custom WKWebView view without having to explicitly trigger the main thread (@MainActor)

103 Views Asked by At

I have a custom WKWebView that I want to utilise in my code:

public class AuthenticatedWebView: WKWebView, AdInAuthenticatedWebView {
    private var shouldStopFurtherRedirects = false
    public weak var authDelegate: AuthenticatedWebViewDelegate?
    private let authenticationService = AuthenticationServiceProvider.service

    public init() {
        super.init(frame: .zero, configuration: WKWebViewConfiguration.config)
        setup()
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    private func setup() {
        navigationDelegate = self
        shouldStopFurtherRedirects = false
    }

    public func authenticate() {
        authenticationService.webSessionURL(redirectURL: nil, completion: { url, error in
            if let url = url {
                let request = URLRequest(url: url)
                self.load(request)
            } else {
                self.authDelegate?.webView(self, authenticationDidFailWithError: error)
            }
        })
    }
}

When I try to initialise this view in my code I get an error:

init(delegate: AdInAuthenticatedWebViewServiceDelegate?) {
        authDelegate = AdInAuthenticatedWebViewServiceDelegateWrapper()
        authDelegate?.adInDelegate = delegate
        authWebView = AuthenticatedWebView()
        authWebView.authDelegate = authDelegate
}

Call to main actor-isolated initializer 'init()' in a synchronous nonisolated context Main actor-isolated property 'authDelegate' can not be mutated from a non-isolated context

I am using the exact same implementation of custom web view in another place in my project where I don't get this error and when I check the documentation for WKWebView, it doesn't seem to have a @MainActor requirement for its init function.

How can I fix this error?

I have confirmed that this issue is because of the inheritance from WKWebView but so far I didn't have any luck in removing this error. I have a similar implementation in another project where it seems to work without errors.

0

There are 0 best solutions below