0

Hi I'm currently using WKWebView in my Swift 3 project. Is it possible to keep the same WKWebView in another class, so that you are running one main WKWebView in different classes?

I've tried to do this with WKProcessPool and WKWebsiteDataStorage, but when I setup a new WKWebView in the other class I don't know how to reference to the existing configuration/logged in wkwebview.

I've looked all over the internet but couldn't find a solution. I hope you understand my problem and know a solution. Thanks in advance!!

Stef
  • 973
  • 1
  • 8
  • 12
  • Not exactly sure what you're going for here. Are you trying to use one instance of the same `WKWebView` across multiple classes, or are you simply trying to reuse one reusable `WKWebView` class with new instances each time? – ZGski Sep 27 '17 at 19:13
  • Danke Steffen du Pfeiffe ich hab jetzt genau das gleiche Problem :D – 最白目 May 13 '19 at 12:14

1 Answers1

4

Stef. If you want to use the same configuration for all web view instances, just create class or extension with a static property/method. For example:

extension WKWebViewConfiguration {
    static var shared : WKWebViewConfiguration {
        if _sharedConfiguration == nil {
            _sharedConfiguration = WKWebViewConfiguration()
            _sharedConfiguration.websiteDataStore = WKWebsiteDataStore.default()
            _sharedConfiguration.userContentController = WKUserContentController()
            _sharedConfiguration.preferences.javaScriptEnabled = true
            _sharedConfiguration.preferences.javaScriptCanOpenWindowsAutomatically = false
        }
        return _sharedConfiguration
    }
    private static var _sharedConfiguration : WKWebViewConfiguration!
}

If you want only share cookies between web view instances, use singleton object by WKWebsiteDataStore.default() for your WKWebViewConfiguration instances.

  • This worked Eldar! Thanks a lot, couldn't find this anywhere on the internet! Nice method! – Stef Sep 29 '17 at 16:40