如何在WKWebview iOS 12中注入cookie

时间:2018-12-24 14:28:27

标签: swift cookies wkwebview

我有一个具有登录名的网站,我正在尝试设置WKWebView,并且我必须存储和还原cookie以维持用户的会话,但是当我在wkwebview中注入存储的cookie时,用户必须再次登录!

我试图将Cookie插入代码的不同部分,但无济于事...

override func viewDidLoad() {
    super.viewDidLoad()

    webView.uiDelegate = self
    webView.navigationDelegate = self


    self.webView.addObserver(self, forKeyPath: "URL", options: .new, context: nil)

    loadCookies()
    let myURL = URL(string:"http://staging.futurjob.it/dashboard")

    let myRequest = URLRequest(url: myURL!)

    webView.load(myRequest)

    imageHeaderContainer.alpha = 0
    btnBack.alpha = 0
    btnForward.alpha = 0

    imageHeaderContainer.frame.origin.y -= 100
    btnBack.frame.origin.y -= 56
    btnForward.frame.origin.y -= 56

    UIView.animate(withDuration: 0.6) {

        self.imageHeaderContainer.alpha = 1
        self.btnBack.alpha = 1
        self.btnForward.alpha = 1

        self.imageHeaderContainer.frame.origin.y += 100
        self.btnBack.frame.origin.y += 56
        self.btnForward.frame.origin.y += 56
    }

    btnForward.dropShadow()
    btnBack.dropShadow()
}

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    saveCookies()
}

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        saveCookies()
}


func saveCookies() {

    let cookieJar: HTTPCookieStorage = HTTPCookieStorage.shared
    if let cookies = cookieJar.cookies {
        let data: Data = NSKeyedArchiver.archivedData(withRootObject: cookies)
        let ud: UserDefaults = UserDefaults.standard
        ud.set(data, forKey: "cookie")
    }

    if #available(iOS 11.0, *) {
        webView.configuration.websiteDataStore.httpCookieStore.getAllCookies { cookies in
            for aCookie in cookies {
                HTTPCookieStorage.shared.setCookie(aCookie)
            }

            print(cookies)

        }
    }
}

func loadCookies() {
    let ud: UserDefaults = UserDefaults.standard
    let data: Data? = ud.object(forKey: "cookie") as? Data
    if let cookie = data {
        let datas: NSArray? = NSKeyedUnarchiver.unarchiveObject(with: cookie) as? NSArray
        if let cookies = datas {
            for c in cookies {
                if let cookieObject = c as? HTTPCookie {
                    HTTPCookieStorage.shared.setCookie(cookieObject)
                }
            }
        }
    }

    if #available(iOS 11.0, *) {
        let cookies = HTTPCookieStorage.shared.cookies ?? []
        for cookie in cookies {
            webView.configuration.websiteDataStore.httpCookieStore.setCookie(cookie)
        }
    }


}
}

我希望用户的会话已被设置。

1 个答案:

答案 0 :(得分:0)

检查以下内容:https://forums.developer.apple.com/thread/99674,WkWebView的cookie存在问题,已经存在的WKWebview有时会忽略设置的cookie。解决方法是先设置cookie,然后创建WKWebView