title: Issue when setting cookies of WKWebView by copying cookies from HTTPCookieStorage to WKWebsiteDataStore
body: <p>I want to show a website in a WKWebView in my iOS app for which I need to set specific http cookies for the user's session. The cookies are already stored in the shared HttpCookieStorage of the app.</p>
  
  <p>At the moment, I try to copy them from there to the WKWebsiteDataStore of the web view before loading the website with the following code:</p>
  
  <pre><code>class ViewerViewController: UIViewController {
  
      // MARK: - Properties
      var webView: WKWebView!
  
      // MARK: - Life Cycle
      override func loadView() {
          webView = WKWebView()
          view = webView
      }
  
      override func viewDidLoad() {
          super.viewDidLoad()
  
          addCookiesToWebView {
              print("Load website")
              if let url = Bundle.main.url(forResource: "MyWebsite", withExtension: "html"), let html = try? String(contentsOf: url) {
                  self.webView.loadHTMLString(html, baseURL: url)
              }
          }   
      }
  
      // MARK: - Functions
      func addCookiesToWebView(completionHandler: @escaping (() -&gt; Void)) {
          let sharedCookies = HTTPCookieStorage.shared.cookies!
          let webViewCookieStore = webView.configuration.websiteDataStore.httpCookieStore
          var count = 0
          sharedCookies.forEach { cookie in
              DispatchQueue.main.async {
                  webViewCookieStore.setCookie(cookie) {
                      count += 1
                      print("Added cookie \(cookie.name)")
                      if count == sharedCookies.count {
                          completionHandler()
                      }
                  }
              }
          }
      }
  }
  </code></pre>
  
  <p>Now, what is incomprehensible for me, is that this sometimes works and the user is authenticated in his user session, but sometimes it doesn't.</p>
  
  <p>It seems like there might be a race condition that leads to the web view loading the website before all the cookies have been copied? When I researched this problem I noticed that other people have problems with cookies in WKWebView as well, but I didn't find any solution so far that actually solves my issue.</p>
  
  <p>Is there a bug in my code or is there a better approach for copying multiple cookies from HttpCookieStorage to a WKWebView?</p>