Reputation: 451
I want to create an app with multiple tab bar. But each tabs, i am going to use Web view.
Questions:
Can someone help me with best approach. I am new to swift and iOS.
Upvotes: 0
Views: 1237
Reputation: 1538
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.
Upvotes: 2
Reputation: 877
The same object can be used at multiple places, either you need to create a copy of the object or create a new object of the class. and implement a way to keep both in sync.
Upvotes: 0