Search code examples
iosobjective-cswiftxcodewkwebview

How do we use same WKWebView for multiple UITab


I want to create an app with multiple tab bar. But each tabs, i am going to use Web view.

Questions:

  1. Is it possible to use same WKWebView(Reuse)?. How do I do that?.

Can someone help me with best approach. I am new to swift and iOS.


Solution

  • So how I see, your biggest problem, that why you want to reuse WKWebView on every tab is sharing cookies:

    In this case, we can avoid reuse and create a kind of cookie manager:

    // SharedCookieManager.swift
    
    
    final class SharedCookieManager: NSObject {
        
        // Singleton manager
        static let `default` = SharedCookieManager()
        private override init() { super.init() }
        
        // All cookies taht we have on every WKWebView
        var cookies: Set<HTTPCookie> = []
        // Callback helping to observe changes in our set
        var cookieUpdateCallback: ((_ cookies: [HTTPCookie]) -> Void)?
        
        // Append method
        func appendCookies(_ cookies: [HTTPCookie]) {
            cookies.forEach({ [weak self] in
                self?.cookies.insert($0)
            })
        }
    }
    

    Use cases of our manager:

    
    // FirstTabViewController.swift
    
    class FirstTabViewController: UIViewController, WKHTTPCookieStoreObserver {
        
        var webView: WKWebView? {
            didSet {
                SharedCookieManager.default.cookieUpdateCallback = { [weak self] newCookies in
                    self?.webView?.configuration.websiteDataStore.httpCookieStore.getAllCookies({ oldCookies in
                        Set(newCookies).symmetricDifference(oldCookies).forEach({
                            self?.webView?.configuration.websiteDataStore.httpCookieStore.setCookie($0, completionHandler: nil)
                        })
                        self?.webView?.reload()
                    })
                }
            }
        }
        
        override func viewDidLoad() {
            super.viewDidLoad()
            
            WKWebsiteDataStore.default().httpCookieStore.add(self)
            let webView = WKWebView()
            
            SharedCookieManager.default.cookies.forEach({ [weak webView] in
                webView?.configuration.websiteDataStore.httpCookieStore.setCookie($0)
            })
        }
        
        func cookiesDidChange(in cookieStore: WKHTTPCookieStore) {
            cookieStore.getAllCookies({
                SharedCookieManager.default.appendCookies($0)
            })
        }
    }
    

    Same for every ViewController you use within TabBar

    It's not a "golden hammer" and I can't say it would work for 100%, but you can try to play with this sample to reach your goals. Hope it will help.