[ios] Can I set the cookies to be used by a WKWebView?

The reason behind posted this answer is I tried many solution but no one work properly, most of the answer not work in case where have to set cookie first time, and got result cookie not sync first time, Please use this solution it work for both iOS >= 11.0 <= iOS 11 till 8.0, also work with cookie sync first time.

For iOS >= 11.0 -- Swift 4.2

Get http cookies and set in wkwebview cookie store like this way, it's very tricky point to load your request in wkwebview, must sent request for loading when cookies gonna be set completely, here is function that i wrote.

Call function with closure in completion you call load webview. FYI this function only handle iOS >= 11.0

self.WwebView.syncCookies {
    if let request = self.request {
       self.WwebView.load(request)
    }
}

Here is implementation for syncCookies function.

func syncCookies(completion:@escaping ()->Void) {

if #available(iOS 11.0, *) {

      if let yourCookie = "HERE_YOUR_HTTP_COOKIE_OBJECT" {
        self.configuration.websiteDataStore.httpCookieStore.setCookie(yourCookie, completionHandler: {
              completion()
        })
     }
  } else {
  //Falback just sent 
  completion()
}
}

For iOS 8 till iOS 11

you need to setup some extra things you need to set two time cookies one through using WKUserScript and dont forget to add cookies in request as well, otherwise your cookie not sync first time and you will see you page not load first time properly. this is the heck that i found to support cookies for iOS 8.0

before you Wkwebview object creation.

func setUpWebView() {

    let userController: WKUserContentController = WKUserContentController.init()

    if IOSVersion.SYSTEM_VERSION_LESS_THAN(version: "11.0") {
        if let cookies = HTTPCookieStorage.shared.cookies {
            if let script = getJSCookiesString(for: cookies) {
                cookieScript = WKUserScript(source: script, injectionTime: .atDocumentStart, forMainFrameOnly: false)
                userController.addUserScript(cookieScript!)
            }
        }
    }

    let webConfiguration = WKWebViewConfiguration()
    webConfiguration.processPool = BaseWebViewController.processPool


    webConfiguration.userContentController = userController


    let customFrame = CGRect.init(origin: CGPoint.zero, size: CGSize.init(width: 0.0, height: self.webContainerView.frame.size.height))
    self.WwebView = WKWebView (frame: customFrame, configuration: webConfiguration)
    self.WwebView.translatesAutoresizingMaskIntoConstraints = false
    self.webContainerView.addSubview(self.WwebView)
    self.WwebView.uiDelegate = self
    self.WwebView.navigationDelegate = self
    self.WwebView.allowsBackForwardNavigationGestures = true // A Boolean value indicating whether horizontal swipe gestures will trigger back-forward list navigations
    self.WwebView.addObserver(self, forKeyPath: #keyPath(WKWebView.estimatedProgress), options: .new, context: nil)


 self.view.addConstraint(NSLayoutConstraint(item: WwebView, attribute: .trailing, relatedBy: .equal, toItem: self.webContainerView, attribute: .trailing, multiplier: 1, constant: 0))
    self.view.addConstraint(NSLayoutConstraint(item: WwebView, attribute: .leading, relatedBy: .equal, toItem: self.webContainerView, attribute: .leading, multiplier: 1, constant: 0))
    self.view.addConstraint(NSLayoutConstraint(item: WwebView, attribute: .top, relatedBy: .equal, toItem: self.webContainerView, attribute: .top, multiplier: 1, constant: 0))
    self.view.addConstraint(NSLayoutConstraint(item: WwebView, attribute: .bottom, relatedBy: .equal, toItem: self.webContainerView, attribute: .bottom, multiplier: 1, constant: 0))


}

Focus on this function getJSCookiesString

 public func getJSCookiesString(for cookies: [HTTPCookie]) -> String? {

    var result = ""
    let dateFormatter = DateFormatter()
    dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
    dateFormatter.dateFormat = "EEE, d MMM yyyy HH:mm:ss zzz"

    for cookie in cookies {
        if cookie.name == "yout_cookie_name_want_to_sync" {
            result += "document.cookie='\(cookie.name)=\(cookie.value); domain=\(cookie.domain); path=\(cookie.path); "
            if let date = cookie.expiresDate {
                result += "expires=\(dateFormatter.string(from: date)); "
            }
            if (cookie.isSecure) {
                result += "secure; "
            }
            result += "'; "
        }

    }

    return result
}

Here is other step wkuserscript not sync cookies immediately, there a lot of heck to load first time page with cookie one is to reload webview again if it terminate process but i don't recommend to use it, its not good for user point of view, heck is whenever you ready to load request set cookies in request header as well like this way, don't forget to add iOS version check. before load request call this function.

request?.addCookies()

i wrote extension for URLRequest

extension URLRequest {

internal mutating func addCookies() {
    //"appCode=anAuY28ucmFrdXRlbi5yZXdhcmQuaW9zLXpOQlRTRmNiejNHSzR0S0xuMGFRb0NjbUg4Ql9JVWJH;rpga=kW69IPVSYZTo0JkZBicUnFxC1g5FtoHwdln59Z5RNXgJoMToSBW4xAMqtf0YDfto;rewardadid=D9F8CE68-CF18-4EE6-A076-CC951A4301F6;rewardheader=true"
    var cookiesStr: String = ""

    if IOSVersion.SYSTEM_VERSION_LESS_THAN(version: "11.0") {
        let mutableRequest = ((self as NSURLRequest).mutableCopy() as? NSMutableURLRequest)!
        if let yourCookie = "YOUR_HTTP_COOKIE_OBJECT" {
            // if have more than one cookies dont forget to add ";" at end
            cookiesStr += yourCookie.name + "=" + yourCookie.value + ";"

            mutableRequest.setValue(cookiesStr, forHTTPHeaderField: "Cookie")
            self = mutableRequest as URLRequest

        }
    }

  }
}

now you ready to go for testing iOS > 8

Examples related to ios

Adding a UISegmentedControl to UITableView Crop image to specified size and picture location Undefined Symbols error when integrating Apptentive iOS SDK via Cocoapods Keep placeholder text in UITextField on input in IOS Accessing AppDelegate from framework? Autoresize View When SubViews are Added Warp \ bend effect on a UIView? Speech input for visually impaired users without the need to tap the screen make UITableViewCell selectable only while editing Xcode 12, building for iOS Simulator, but linking in object file built for iOS, for architecture arm64

Examples related to cookies

SameSite warning Chrome 77 How to fix "set SameSite cookie to none" warning? Set cookies for cross origin requests Make Axios send cookies in its requests automatically How can I set a cookie in react? Fetch API with Cookie How to use cookies in Python Requests How to set cookies in laravel 5 independently inside controller Where does Chrome store cookies? Sending cookies with postman

Examples related to uiwebview

How to display .svg image using swift Can I set the cookies to be used by a WKWebView? How to Migrate to WKWebView? iOS JavaScript bridge How to load local html file into UIWebView Load resources from relative path using local html in uiwebview Clearing UIWebview cache How to determine the content size of a UIWebView? UIWebView open links in Safari Can we open pdf file using UIWebView on iOS?

Examples related to ios8

Is there any way to show a countdown on the lockscreen of iphone? How to display an activity indicator with text on iOS 8 with Swift? How to call gesture tap on UIView programmatically in swift Changing the Status Bar Color for specific ViewControllers using Swift in iOS8 Can I set the cookies to be used by a WKWebView? UIAlertController custom font, size, color How to force view controller orientation in iOS 8? How to get textLabel of selected row in swift? Launch Image does not show up in my iOS App NavigationBar bar, tint, and title text color in iOS 8

Examples related to wkwebview

com.apple.WebKit.WebContent drops 113 error: Could not find specified service Request Permission for Camera and Library in iOS 10 - Info.plist Can I set the cookies to be used by a WKWebView? How to Migrate to WKWebView?