我尝试将现有应用从UIWebView
切换为WKWebView
。当前应用程序管理webview
之外的用户登录/会话,并将身份验证所需的cookies
设置为NSHTTPCookieStore
。很遗憾,新的WKWebView
并未使用cookies
中的NSHTTPCookieStorage
。还有另一种方法可以达到这个目的吗?
答案 0 :(得分:135)
仅针对iOS 11+进行修改
let cookie = HTTPCookie(properties: [
.domain: "example.com",
.path: "/",
.name: "MyCookieName",
.value: "MyCookieValue",
.secure: "TRUE",
.expires: NSDate(timeIntervalSinceNow: 31556926)
])!
webView.configuration.websiteDataStore.httpCookieStore.setCookie(cookie)
由于您是从HTTPCookeStorage中提取它们,因此可以执行此操作:
let cookies = HTTPCookieStorage.shared.cookies ?? []
for (cookie) in cookies {
webView.configuration.websiteDataStore.httpCookieStore.setCookie(cookie)
}
适用于iOS 10及以下版本的旧答案
如果您需要在初始加载请求中设置cookie,可以在NSMutableURLRequest上设置它们。因为cookie只是一个特殊格式的请求标头,所以可以这样实现:
WKWebView * webView = /*set up your webView*/
NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://example.com/index.html"]];
[request addValue:@"TeskCookieKey1=TeskCookieValue1;TeskCookieKey2=TeskCookieValue2;" forHTTPHeaderField:@"Cookie"];
// use stringWithFormat: in the above line to inject your values programmatically
[webView loadRequest:request];
如果您要求页面上的后续AJAX请求设置其Cookie,只需使用WKUserScript在文档启动时通过javascript以编程方式设置值即可实现:
WKUserContentController* userContentController = WKUserContentController.new;
WKUserScript * cookieScript = [[WKUserScript alloc]
initWithSource: @"document.cookie = 'TeskCookieKey1=TeskCookieValue1';document.cookie = 'TeskCookieKey2=TeskCookieValue2';"
injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];
// again, use stringWithFormat: in the above line to inject your values programmatically
[userContentController addUserScript:cookieScript];
WKWebViewConfiguration* webViewConfig = WKWebViewConfiguration.new;
webViewConfig.userContentController = userContentController;
WKWebView * webView = [[WKWebView alloc] initWithFrame:CGRectMake(/*set your values*/) configuration:webViewConfig];
结合这两种技术应该为您提供足够的工具,将Cookie值从Native App Land传输到Web View Land。如果您需要更高级的Cookie,可以在cookie javascript API on Mozilla's page上找到更多信息。
是的,很糟糕的是Apple并没有支持很多the niceties of UIWebView。不确定他们是否会支持他们,但希望他们能尽快得到这个。希望这有帮助!
答案 1 :(得分:57)
在玩this answer之后(这非常有用:)我们不得不做一些改变:
NSHTTPCookieStorage
所以我们修改了我们的代码;
NSMutableURLRequest *request = [originalRequest mutableCopy];
NSString *validDomain = request.URL.host;
const BOOL requestIsSecure = [request.URL.scheme isEqualToString:@"https"];
NSMutableArray *array = [NSMutableArray array];
for (NSHTTPCookie *cookie in [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]) {
// Don't even bother with values containing a `'`
if ([cookie.name rangeOfString:@"'"].location != NSNotFound) {
NSLog(@"Skipping %@ because it contains a '", cookie.properties);
continue;
}
// Is the cookie for current domain?
if (![cookie.domain hasSuffix:validDomain]) {
NSLog(@"Skipping %@ (because not %@)", cookie.properties, validDomain);
continue;
}
// Are we secure only?
if (cookie.secure && !requestIsSecure) {
NSLog(@"Skipping %@ (because %@ not secure)", cookie.properties, request.URL.absoluteString);
continue;
}
NSString *value = [NSString stringWithFormat:@"%@=%@", cookie.name, cookie.value];
[array addObject:value];
}
NSString *header = [array componentsJoinedByString:@";"];
[request setValue:header forHTTPHeaderField:@"Cookie"];
// Now perform the request...
这可以确保第一个请求设置了正确的cookie,而不从共享存储中发送任何用于其他域的cookie,也不会将任何安全cookie发送到不安全的请求中。
我们还需要确保其他请求设置了Cookie。这是使用在文档加载上运行的脚本来完成的,该脚本检查是否存在cookie集,如果没有,则将其设置为NSHTTPCookieStorage
中的值。
// Get the currently set cookie names in javascriptland
[script appendString:@"var cookieNames = document.cookie.split('; ').map(function(cookie) { return cookie.split('=')[0] } );\n"];
for (NSHTTPCookie *cookie in [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]) {
// Skip cookies that will break our script
if ([cookie.value rangeOfString:@"'"].location != NSNotFound) {
continue;
}
// Create a line that appends this cookie to the web view's document's cookies
[script appendFormat:@"if (cookieNames.indexOf('%@') == -1) { document.cookie='%@'; };\n", cookie.name, cookie.wn_javascriptString];
}
WKUserContentController *userContentController = [[WKUserContentController alloc] init];
WKUserScript *cookieInScript = [[WKUserScript alloc] initWithSource:script
injectionTime:WKUserScriptInjectionTimeAtDocumentStart
forMainFrameOnly:NO];
[userContentController addUserScript:cookieInScript];
...
// Create a config out of that userContentController and specify it when we create our web view.
WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
config.userContentController = userContentController;
self.webView = [[WKWebView alloc] initWithFrame:webView.bounds configuration:config];
我们还需要处理服务器更改cookie的值。这意味着添加另一个脚本来回调我们正在创建的网页视图,以更新我们的NSHTTPCookieStorage
。
WKUserScript *cookieOutScript = [[WKUserScript alloc] initWithSource:@"window.webkit.messageHandlers.updateCookies.postMessage(document.cookie);"
injectionTime:WKUserScriptInjectionTimeAtDocumentStart
forMainFrameOnly:NO];
[userContentController addUserScript:cookieOutScript];
[userContentController addScriptMessageHandler:webView
name:@"updateCookies"];
并实施委托方法来更新任何已更改的Cookie,确保我们只更新当前域中的Cookie!
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
NSArray<NSString *> *cookies = [message.body componentsSeparatedByString:@"; "];
for (NSString *cookie in cookies) {
// Get this cookie's name and value
NSArray<NSString *> *comps = [cookie componentsSeparatedByString:@"="];
if (comps.count < 2) {
continue;
}
// Get the cookie in shared storage with that name
NSHTTPCookie *localCookie = nil;
for (NSHTTPCookie *c in [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:self.wk_webView.URL]) {
if ([c.name isEqualToString:comps[0]]) {
localCookie = c;
break;
}
}
// If there is a cookie with a stale value, update it now.
if (localCookie) {
NSMutableDictionary *props = [localCookie.properties mutableCopy];
props[NSHTTPCookieValue] = comps[1];
NSHTTPCookie *updatedCookie = [NSHTTPCookie cookieWithProperties:props];
[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:updatedCookie];
}
}
}
这似乎解决了我们的cookie问题,而我们不必处理我们使用WKWebView的每个地方。我们现在可以使用此代码作为帮助来创建我们的Web视图,并为我们透明地更新NSHTTPCookieStorage
。
编辑:结果我在NSHTTPCookie上使用了一个私人类别 - 这是代码:
- (NSString *)wn_javascriptString {
NSString *string = [NSString stringWithFormat:@"%@=%@;domain=%@;path=%@",
self.name,
self.value,
self.domain,
self.path ?: @"/"];
if (self.secure) {
string = [string stringByAppendingString:@";secure=true"];
}
return string;
}
答案 2 :(得分:24)
必须在创建WKWebView
之前在配置上设置Cookie。否则,即使使用WKHTTPCookieStore
setCookie
完成处理程序,Cookie也无法可靠地同步到网络视图。这可以从WKWebViewConfiguration
@NSCopying var configuration: WKWebViewConfiguration { get }
@NSCopying
有点深刻。实施超出了我的要求,但最终的结果是,除非您在初始化webview之前设置了cookie,否则您无法依赖那里的cookie。这会使app体系结构复杂化,因为初始化视图会变成异步过程。你最终会得到像这样的东西
extension WKWebViewConfiguration {
/// Async Factory method to acquire WKWebViewConfigurations packaged with system cookies
static func cookiesIncluded(completion: @escaping (WKWebViewConfiguration?) -> Void) {
let config = WKWebViewConfiguration()
guard let cookies = HTTPCookieStorage.shared.cookies else {
completion(config)
return
}
// Use nonPersistent() or default() depending on if you want cookies persisted to disk
// and shared between WKWebViews of the same app (default), or not persisted and not shared
// across WKWebViews in the same app.
let dataStore = WKWebsiteDataStore.nonPersistent()
let waitGroup = DispatchGroup()
for cookie in cookies {
waitGroup.enter()
dataStore.httpCookieStore.setCookie(cookie) { waitGroup.leave() }
}
waitGroup.notify(queue: DispatchQueue.main) {
config.websiteDataStore = dataStore
completion(config)
}
}
}
然后使用类似
的东西override func loadView() {
view = UIView()
WKWebViewConfiguration.cookiesIncluded { [weak self] config in
let webView = WKWebView(frame: .zero, configuration: webConfiguration)
webView.load(request)
self.view = webView
}
}
上面的例子将视图创建推迟到最后一刻,另一个解决方案是提前创建配置或webview并在创建视图控制器之前处理异步性质。
最后一点:一旦你创建了这个webview,就可以将它放到野外,你不能在不使用this answer中描述的方法的情况下添加更多的cookie。但是,您可以使用WKHTTPCookieStoreObserver
api来至少观察Cookie发生的变化。因此,如果会话cookie在网页浏览中得到更新,您可以根据需要使用此新Cookie手动更新系统HTTPCookieStorage
。
有关详情,请跳至此2017 WWDC Session Custom Web Content Loading的18:00。在本课程开始时,有一个欺骗性的代码示例,它省略了应该在完成处理程序中创建webview的事实。
cookieStore.setCookie(cookie!) {
webView.load(loggedInURLRequest)
}
18:00的现场演示澄清了这一点。
编辑至少从Mojave Beta 7和iOS 12 Beta 7开始,我发现使用Cookie的行为更加一致。 setCookie(_:)
方法甚至似乎允许在创建WKWebView
后设置Cookie。我确实觉得很重要,根本不会触及 processPool
变量。如果没有创建其他池并且该属性保持单独,则cookie设置功能最有效。我认为可以肯定地说,由于WebKit中的一些错误,我们遇到了问题。
答案 3 :(得分:18)
以下是我在Swift中的Mattrs解决方案版本,用于从HTTPCookieStorage注入所有Cookie。这主要是为了注入一个身份验证cookie来创建一个用户会话。
public func setupWebView() {
let userContentController = WKUserContentController()
if let cookies = HTTPCookieStorage.shared.cookies {
let script = getJSCookiesString(for: cookies)
let cookieScript = WKUserScript(source: script, injectionTime: .atDocumentStart, forMainFrameOnly: false)
userContentController.addUserScript(cookieScript)
}
let webViewConfig = WKWebViewConfiguration()
webViewConfig.userContentController = userContentController
self.webView = WKWebView(frame: self.webViewContainer.bounds, configuration: webViewConfig)
}
///Generates script to create given cookies
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 {
result += "document.cookie='\(cookie.name)=\(cookie.value); domain=\(cookie.domain); path=\(cookie.path); "
if let date = cookie.expiresDate {
result += "expires=\(dateFormatter.stringFromDate(date)); "
}
if (cookie.secure) {
result += "secure; "
}
result += "'; "
}
return result
}
答案 4 :(得分:9)
Swift 3更新:
func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
if let urlResponse = navigationResponse.response as? HTTPURLResponse,
let url = urlResponse.url,
let allHeaderFields = urlResponse.allHeaderFields as? [String : String] {
let cookies = HTTPCookie.cookies(withResponseHeaderFields: allHeaderFields, for: url)
HTTPCookieStorage.shared.setCookies(cookies , for: urlResponse.url!, mainDocumentURL: nil)
decisionHandler(.allow)
}
}
答案 5 :(得分:7)
设置Cookie
self.webView.evaluateJavaScript("document.cookie='access_token=your token';domain='your domain';") { (data, error) -> Void in
self.webView.reload()
}
删除Cookie
self.webView.evaluateJavaScript("document.cookie='access_token=';domain='your domain';") { (data, error) -> Void in
self.webView.reload()
}
答案 6 :(得分:7)
在iOS 11中,您现在可以管理cookie :),请参阅此会话:https://developer.apple.com/videos/play/wwdc2017/220/
答案 7 :(得分:5)
在查看了各种答案并且没有取得任何成功后,我梳理了WebKit文档并偶然发现了HTTPCookie
上的URLRequest
静态方法,该方法将一组cookie转换为适合的格式标题字段。将此与var request = URLRequest(url: URL(string: "https://example.com/")!)
let headers = HTTPCookie.requestHeaderFields(with: cookies)
for (name, value) in headers {
request.addValue(value, forHTTPHeaderField: name)
}
let webView = WKWebView(frame: self.view.frame)
webView.load(request)
更新extension WKWebView {
func load(_ request: URLRequest, with cookies: [HTTPCookie]) {
var request = request
let headers = HTTPCookie.requestHeaderFields(with: cookies)
for (name, value) in headers {
request.addValue(value, forHTTPHeaderField: name)
}
load(request)
}
}
并将其加载到Cookie标头之前将其结合起来,让我完成了最后一行。
let request = URLRequest(url: URL(string: "https://example.com/")!)
let webView = WKWebView(frame: self.view.frame)
webView.load(request, with: cookies)
为了使这更简单,请使用扩展名:
message M1 {
repeated M2 mylist = 1;
}
message M2 {
repeated string mylist = 1;
}
现在它变成了:
List<M2>
如果您只想要一个插入式解决方案,也可以在mattr's insight中使用此扩展程序。干杯!
答案 8 :(得分:3)
发布此答案的原因是我尝试了许多解决方案,但没有人能正常工作,大多数答案在必须先设置Cookie且第一次未获得结果Cookie的情况下不起作用,请使用此解决方案适用于两个iOS> = 11.0 <= iOS 11直到8.0,还可以首次使用Cookie同步。
对于iOS> = 11.0 -Swift 4.2
以这种方式获取 http cookie 并在 wkwebview cookie存储中进行设置,将请求加载到 wkwebview 是非常棘手的一点,必须发送要求完全设置cookie时加载的请求,这是我编写的函数。
带有关闭的调用功能完成后,您将调用load webview。仅供参考,此功能仅处理iOS> = 11.0
self.WwebView.syncCookies {
if let request = self.request {
self.WwebView.load(request)
}
}
这是 syncCookies 函数的实现。
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()
}
}
对于iOS 8至iOS 11
您需要设置一些额外的东西,您需要使用 WKUserScript 来设置两次Cookie,并且不要忘记在请求中添加cookie,否则您的cookie不会第一次同步,您将看到您的页面第一次无法正确加载。这是我发现支持iOS 8.0的Cookie的难处
在创建Wkwebview对象之前。
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))
}
关注此功能 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
}
这是其他步骤wkuserscript不能立即同步cookie,用cookie加载第一次页面有很多麻烦,如果终止进程,则是重新加载webview,但是我不建议使用它,这对用户不利从角度上讲,无论何时您准备将请求集cookie加载到请求标头中的方式都一样,别忘了添加iOS版本检查。在加载请求之前调用此函数。
request?.addCookies()
我为 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
}
}
}
}
现在您准备好测试iOS> 8
答案 9 :(得分:2)
请找到最有可能为您提供解决方案的解决方案。基本上它已经针对Swift 4 @ user3589213 &#39; s answer进行了修改和更新。
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
let headerKeys = navigationAction.request.allHTTPHeaderFields?.keys
let hasCookies = headerKeys?.contains("Cookie") ?? false
if hasCookies {
decisionHandler(.allow)
} else {
let cookies = HTTPCookie.requestHeaderFields(with: HTTPCookieStorage.shared.cookies ?? [])
var headers = navigationAction.request.allHTTPHeaderFields ?? [:]
headers += cookies
var req = navigationAction.request
req.allHTTPHeaderFields = headers
webView.load(req)
decisionHandler(.cancel)
}
}
答案 10 :(得分:2)
我对nteiss的回答。在iOS 11, 12, 13
上进行了测试。看来您不必再在DispatchGroup
上使用iOS 13
。
我在includeCustomCookies
上使用了非静态函数WKWebViewConfiguration
,因此每次创建新的cookies
时都可以更新WKWebViewConfiguration
。
extension WKWebViewConfiguration {
func includeCustomCookies(cookies: [HTTPCookie], completion: @escaping () -> Void) {
let dataStore = WKWebsiteDataStore.nonPersistent()
let waitGroup = DispatchGroup()
for cookie in cookies {
waitGroup.enter()
dataStore.httpCookieStore.setCookie(cookie) { waitGroup.leave() }
}
waitGroup.notify(queue: DispatchQueue.main) {
self.websiteDataStore = dataStore
completion()
}
}
}
然后我像这样使用它:
let customUserAgent: String = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.1.1 Safari/605.1.15"
let customCookies: [HTTPCookie] = {
let cookie1 = HTTPCookie(properties: [
.domain: "yourdomain.com",
.path: "/",
.name: "auth_token",
.value: APIManager.authToken
])!
let cookie2 = HTTPCookie(properties: [
.domain: "yourdomain.com",
.path: "/",
.name: "i18next",
.value: "ru"
])!
return [cookie1, cookie2]
}()
override func viewDidLoad() {
super.viewDidLoad()
activityIndicatorView.startAnimating()
let webConfiguration = WKWebViewConfiguration()
webConfiguration.includeCustomCookies(cookies: customCookies, completion: { [weak self] in
guard let strongSelf = self else { return }
strongSelf.webView = WKWebView(frame: strongSelf.view.bounds, configuration: webConfiguration)
strongSelf.webView.customUserAgent = strongSelf.customUserAgent
strongSelf.webView.navigationDelegate = strongSelf
strongSelf.webView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
strongSelf.view.addSubview(strongSelf.webView)
strongSelf.view.bringSubviewToFront(strongSelf.activityIndicatorView)
strongSelf.webView.load(strongSelf.request)
})
}
答案 11 :(得分:1)
终于得到了适用于 ios 11+ 的解决方案。在这里粘贴我的代码...
extension WKWebViewConfiguration {
static func includeCookie(preferences:WKPreferences, completion: @escaping (WKWebViewConfiguration?) -> Void) {
let config = WKWebViewConfiguration()
guard let cookies = HTTPCookieStorage.shared.cookies else {
completion(config)
return
}
config.preferences = preferences
let dataStore = WKWebsiteDataStore.nonPersistent()
HTTPCookieStorage.shared.cookieAcceptPolicy = .always
DispatchQueue.main.async {
let waitGroup = DispatchGroup()
for cookie in cookies{
waitGroup.enter()
let customCookie = HTTPCookie(properties: [
.domain: cookie.domain,
.path: cookie.path,
.name: cookie.name,
.value: cookie.value,
.secure: cookie.isSecure,
.expires: cookie.expiresDate ?? NSDate(timeIntervalSinceNow: 31556926)
])
if let cookieData = customCookie{
dataStore.httpCookieStore.setCookie(cookieData) {
waitGroup.leave()
}
}
}
waitGroup.notify(queue: DispatchQueue.main) {
config.websiteDataStore = dataStore
completion(config)
}
}
}
}
在 WKWebViewConfiguration 中设置 cookie 后,使用相同的 config 加载 webview...
WKWebViewConfiguration.includeCookie(preferences: preferences, completion: {
[weak self] config in
if let `self` = self {
if let configuration = config {
webview = WKWebView(frame: self.contentView.bounds, configuration: config)
webview.configuration.websiteDataStore.httpCookieStore.getAllCookies { (response) in
print("")
}
self.contentView.addSubview(webview)
if let filePath = Bundle.main.url(forResource: "index", withExtension: "html", subdirectory: "packageDetailWevview") {
if let requestUrl = filePath {
let request = URLRequest(url: requestUrl)
webview.load(request)
}
}
}
}
})
答案 12 :(得分:0)
这对我有用: 在setcookies之后,添加fetchdatarecords
let cookiesSet = NetworkProvider.getCookies(forKey :
PaywallProvider.COOKIES_KEY, completionHandler: nil)
let dispatchGroup = DispatchGroup()
for (cookie) in cookiesSet {
if #available(iOS 11.0, *) {
dispatchGroup.enter()
self.webView.configuration.websiteDataStore.httpCookieStore.setCookie(cookie){
dispatchGroup.leave()
print ("cookie added: \(cookie.description)")
}
} else {
// TODO Handle ios 10 Fallback on earlier versions
}
}
dispatchGroup.notify(queue: .main, execute: {
self.webView.configuration.websiteDataStore.fetchDataRecords(ofTypes:
WKWebsiteDataStore.allWebsiteDataTypes()) { records in
records.forEach { record in
print("[WebCacheCleaner] Record \(record)")
}
self.webView.load(URLRequest(url:
self.dataController.premiumArticleURL ,
cachePolicy:NSURLRequest.CachePolicy.reloadIgnoringLocalAndRemoteCacheData,
timeoutInterval: 10.0))
}
})
}
答案 13 :(得分:0)
我已经尝试了以上所有答案,但是都没有用。经过如此多的尝试,我终于找到了一种可靠的方式来设置WKWebview cookie。
首先,您必须创建WKProcessPool的实例并将其设置为WKWebViewConfiguration,该实例将用于初始化WkWebview本身:
private lazy var mainWebView: WKWebView = {
let webConfiguration = WKWebViewConfiguration()
webConfiguration.processPool = WKProcessPool()
let webView = WKWebView(frame: .zero, configuration: webConfiguration)
webView.navigationDelegate = self
return webView
}()
在这里设置WKProcessPool是最重要的步骤。 WKWebview利用进程隔离-这意味着它在与应用程序进程不同的进程上运行。有时这可能会导致冲突并阻止您的cookie与WKWebview正确同步。
现在让我们看一下WKProcessPool
的定义与Web视图关联的进程池由其Web视图配置指定。在达到实现定义的过程限制之前,每个Web视图都将拥有自己的Web内容过程。之后,具有相同进程池的Web视图最终将共享Web Content进程。
如果您打算对子序列请求使用相同的WKWebview,请注意最后一句话
具有相同进程池的Web视图最终共享Web内容 流程
我的意思是,如果您在每次为同一域配置WKWebView时都不使用WKProcessPool的相同实例(也许您的VC A包含WKWebView,并且您想创建VC A的不同实例)在不同的位置),可能会有冲突设置cookie。为了解决该问题,在为加载域B的WKWebView首次创建WKProcessPool之后,我将其保存为单例并在每次必须创建加载相同域B的WKWebView时都使用相同的WKProcessPool
private lazy var mainWebView: WKWebView = {
let webConfiguration = WKWebViewConfiguration()
if Enviroment.shared.processPool == nil {
Enviroment.shared.processPool = WKProcessPool()
}
webConfiguration.processPool = Enviroment.shared.processPool!
webConfiguration.processPool = WKProcessPool()
let webView = WKWebView(frame: .zero, configuration: webConfiguration)
webView.navigationDelegate = self
return webView
}()
在初始化过程之后,您可以将URLRequest 装入完成httpCookieStore.setCookie
的中。在这里,您必须将Cookie附加到请求标头上,否则它将无法正常工作。
P / s:我从Dan Loewenherz上面的奇妙答案中窃取了扩展名
mainWebView.configuration.websiteDataStore.httpCookieStore.setCookie(your_cookie) {
self.mainWebView.load(your_request, with: [your_cookie])
}
extension WKWebView {
func load(_ request: URLRequest, with cookies: [HTTPCookie]) {
var request = request
let headers = HTTPCookie.requestHeaderFields(with: cookies)
for (name, value) in headers {
request.addValue(value, forHTTPHeaderField: name)
}
load(request)
}
}
答案 14 :(得分:0)
添加多个Cookie项目时,您可以这样操作:(每个项目都需要path
和domain
)
NSString *cookie = [NSString stringWithFormat:@"document.cookie = 'p1=%@;path=/;domain=your.domain;';document.cookie = 'p2=%@;path=/;domain=your.domain;';document.cookie = 'p3=%@;path=/;domain=your.domain;';", p1_string, p2_string, p3_string];
WKUserScript *cookieScript = [[WKUserScript alloc]
initWithSource:cookie
injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];
[userContentController addUserScript:cookieScript];
否则,将仅设置第一个cookie项目。
答案 15 :(得分:0)
您还可以使用WKWebsiteDataStore从UIWebView获得与HTTPCookieStorage类似的行为。
let dataStore = WKWebsiteDataStore.default()
let cookies = HTTPCookieStorage.shared.cookies ?? [HTTPCookie]()
cookies.forEach({
dataStore.httpCookieStore.setCookie($0, completionHandler: nil)
})
答案 16 :(得分:0)
以下代码在我的项目Swift5中运行良好。 尝试通过下面的WKWebView加载网址:
private func loadURL(urlString: String) {
let url = URL(string: urlString)
guard let urlToLoad = url else { fatalError("Cannot find any URL") }
// Cookies configuration
var urlRequest = URLRequest(url: urlToLoad)
if let cookies = HTTPCookieStorage.shared.cookies(for: urlToLoad) {
let headers = HTTPCookie.requestHeaderFields(with: cookies)
for header in headers { urlRequest.addValue(header.value, forHTTPHeaderField: header.key) }
}
webview.load(urlRequest)
}
答案 17 :(得分:0)
这是我在iOS 9或更高版本中使用Cookies和WKWebView处理的解决方案。
import WebKit
extension WebView {
enum LayoutMode {
case fillContainer
}
func autoLayout(_ view: UIView?, mode: WebView.LayoutMode = .fillContainer) {
guard let view = view else { return }
self.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(self)
switch mode {
case .fillContainer:
NSLayoutConstraint.activate([
self.topAnchor.constraint(equalTo: view.topAnchor),
self.leadingAnchor.constraint(equalTo: view.leadingAnchor),
self.trailingAnchor.constraint(equalTo: view.trailingAnchor),
self.bottomAnchor.constraint(equalTo: view.bottomAnchor)
])
}
}
}
class WebView : WKWebView {
var request : URLRequest?
func load(url: URL, useSharedCookies: Bool = false) {
if useSharedCookies, let cookies = HTTPCookieStorage.shared.cookies(for: url) {
self.load(url: url, withCookies: cookies)
} else {
self.load(URLRequest(url: url))
}
}
func load(url: URL, withCookies cookies: [HTTPCookie]) {
self.request = URLRequest(url: url)
let headers = HTTPCookie.requestHeaderFields(with: cookies)
self.request?.allHTTPHeaderFields = headers
self.load(request!)
}
}
答案 18 :(得分:0)
如果有人在使用Alamofire,那么这是更好的解决方案。
let cookies = Alamofire.SessionManager.default.session.configuration.httpCookieStorage?.cookies(for: URL(string: BASE_URL)!)
for (cookie) in cookies ?? [] {
webView.configuration.websiteDataStore.httpCookieStore.setCookie(cookie)
}
答案 19 :(得分:0)
我正在做的这个错误是我在domain属性中传递了整个url,它应该仅仅是域名。
let cookie = HTTPCookie(properties: [
.domain: "example.com",
.path: "/",
.name: "MyCookieName",
.value: "MyCookieValue",
.secure: "TRUE",
])!
webView.configuration.websiteDataStore.httpCookieStore.setCookie(cookie)
答案 20 :(得分:0)
iOS 10+的解决方案
import UIKit
import WebKit
extension WKWebViewConfiguration {
func set(cookies: [HTTPCookie], completion: (() -> Void)?) {
if #available(iOS 11.0, *) {
let waitGroup = DispatchGroup()
for cookie in cookies {
waitGroup.enter()
websiteDataStore.httpCookieStore.setCookie(cookie) { waitGroup.leave() }
}
waitGroup.notify(queue: DispatchQueue.main) { completion?() }
} else {
cookies.forEach { HTTPCookieStorage.shared.setCookie($0) }
self.createCookiesInjectionJS(cookies: cookies) {
let script = WKUserScript(source: $0, injectionTime: .atDocumentStart, forMainFrameOnly: false)
self.userContentController.addUserScript(script)
DispatchQueue.main.async { completion?() }
}
}
}
private func createCookiesInjectionJS (cookies: [HTTPCookie], completion: ((String) -> Void)?) {
var scripts: [String] = ["var cookieNames = document.cookie.split('; ').map(function(cookie) { return cookie.split('=')[0] } )"]
let now = Date()
for cookie in cookies {
if let expiresDate = cookie.expiresDate, now.compare(expiresDate) == .orderedDescending { continue }
scripts.append("if (cookieNames.indexOf('\(cookie.name)') == -1) { document.cookie='\(cookie.javaScriptString)'; }")
}
completion?(scripts.joined(separator: ";\n"))
}
}
extension WKWebView {
func loadWithCookies(request: URLRequest) {
if #available(iOS 11.0, *) {
load(request)
} else {
var _request = request
_request.setCookies()
load(_request)
}
}
}
extension URLRequest {
private static var cookieHeaderKey: String { "Cookie" }
private static var noAppliedcookieHeaderKey: String { "No-Applied-Cookies" }
var hasCookies: Bool {
let headerKeys = (allHTTPHeaderFields ?? [:]).keys
var hasCookies = false
if headerKeys.contains(URLRequest.cookieHeaderKey) { hasCookies = true }
if !hasCookies && headerKeys.contains(URLRequest.noAppliedcookieHeaderKey) { hasCookies = true }
return hasCookies
}
mutating func setCookies() {
if #available(iOS 11.0, *) { return }
var cookiesApplied = false
if let url = self.url, let cookies = HTTPCookieStorage.shared.cookies(for: url) {
let headers = HTTPCookie.requestHeaderFields(with: cookies)
for (name, value) in headers { setValue(value, forHTTPHeaderField: name) }
cookiesApplied = allHTTPHeaderFields?.keys.contains(URLRequest.cookieHeaderKey) ?? false
}
if !cookiesApplied { setValue("true", forHTTPHeaderField: URLRequest.noAppliedcookieHeaderKey) }
}
}
/// https://github.com/Kofktu/WKCookieWebView/blob/master/WKCookieWebView/WKCookieWebView.swift
extension HTTPCookie {
var javaScriptString: String {
if var properties = properties {
properties.removeValue(forKey: .name)
properties.removeValue(forKey: .value)
return properties.reduce(into: ["\(name)=\(value)"]) { result, property in
result.append("\(property.key.rawValue)=\(property.value)")
}.joined(separator: "; ")
}
var script = [
"\(name)=\(value)",
"domain=\(domain)",
"path=\(path)"
]
if isSecure { script.append("secure=true") }
if let expiresDate = expiresDate {
script.append("expires=\(HTTPCookie.dateFormatter.string(from: expiresDate))")
}
return script.joined(separator: "; ")
}
private static let dateFormatter: DateFormatter = {
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US")
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
dateFormatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss zzz"
return dateFormatter
}()
}
不要忘记在此处粘贴解决方案代码
class WebViewController: UIViewController {
private let host = "google.com"
private weak var webView: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
setupWebView()
}
func setupWebView() {
let cookies: [HTTPCookie] = []
let configuration = WKWebViewConfiguration()
configuration.websiteDataStore = .nonPersistent()
configuration.set(cookies: cookies) {
let webView = WKWebView(frame: .zero, configuration: configuration)
/// ..
self.webView = webView
self.loadPage(url: URL(string:self.host)!)
}
}
private func loadPage(url: URL) {
var request = URLRequest(url: url)
request.setCookies()
webView.load(request)
}
}
extension WebViewController: WKNavigationDelegate {
// https://stackoverflow.com/a/47529039/4488252
func webView(_ webView: WKWebView,
decidePolicyFor navigationAction: WKNavigationAction,
decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
if #available(iOS 11.0, *) {
decisionHandler(.allow)
} else {
guard let url = navigationAction.request.url, let host = url.host, host.contains(self.host) else {
decisionHandler(.allow)
return
}
if navigationAction.request.hasCookies {
decisionHandler(.allow)
} else {
DispatchQueue.main.async {
decisionHandler(.cancel)
self.loadPage(url: url)
}
}
}
}
}
不要忘记在此处粘贴解决方案代码
import UIKit
import WebKit
class ViewController: UIViewController {
private weak var webView: WKWebView!
let url = URL(string: "your_url")!
var cookiesData: [String : Any] {
[
"access_token": "your_token"
]
}
override func viewDidLoad() {
super.viewDidLoad()
let configuration = WKWebViewConfiguration()
guard let host = self.url.host else { return }
configuration.set(cookies: createCookies(host: host, parameters: self.cookiesData)) {
let webView = WKWebView(frame: .zero, configuration: configuration)
self.view.addSubview(webView)
self.webView = webView
webView.navigationDelegate = self
webView.translatesAutoresizingMaskIntoConstraints = false
webView.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true
webView.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true
self.view.bottomAnchor.constraint(equalTo: webView.bottomAnchor).isActive = true
self.view.rightAnchor.constraint(equalTo: webView.rightAnchor).isActive = true
self.loadPage(url: self.url)
}
}
private func loadPage(url: URL) {
var request = URLRequest(url: url)
request.timeoutInterval = 30
request.setCookies()
webView.load(request)
}
private func createCookies(host: String, parameters: [String: Any]) -> [HTTPCookie] {
parameters.compactMap { (name, value) in
HTTPCookie(properties: [
.domain: host,
.path: "/",
.name: name,
.value: "\(value)",
.secure: "TRUE",
.expires: Date(timeIntervalSinceNow: 31556952),
])
}
}
}
extension ViewController: WKNavigationDelegate {
// https://stackoverflow.com/a/47529039/4488252
func webView(_ webView: WKWebView,
decidePolicyFor navigationAction: WKNavigationAction,
decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
if #available(iOS 11.0, *) {
decisionHandler(.allow)
} else {
guard let url = navigationAction.request.url, let host = url.host, host.contains(self.url.host!) else {
decisionHandler(.allow)
return
}
if navigationAction.request.hasCookies {
decisionHandler(.allow)
} else {
DispatchQueue.main.async {
decisionHandler(.cancel)
self.loadPage(url: url)
}
}
}
}
}
添加您的Info.plist传输安全设置
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
答案 21 :(得分:0)
这就是我的做法-
在AppDelegate的didFinishLaunchingWithOptions中调用initWebConfig(或在创建WebView之前的任何位置),否则有时Cookie无法正确同步-
func initWebConfig() {
self.webConfig = WKWebViewConfiguration()
self.webConfig.websiteDataStore = WKWebsiteDataStore.nonPersistent()
}
func setCookie(key: String, value: AnyObject, domain: String? = nil, group: DispatchGroup? = nil) {
let cookieProps: [HTTPCookiePropertyKey : Any] = [
.domain: domain ?? "google.com",
.path: "/",
.name: key,
.value: value,
]
if let cookie = HTTPCookie(properties: cookieProps) {
group?.enter()
let webConfig = (UIApplication.shared.delegate as? AppDelegate)?.webConfig
webConfig?.websiteDataStore.httpCookieStore.setCookie(cookie) {
group?.leave()
}
}
}
在需要的地方,在发送组中设置cookie-
let group = DispatchGroup()
self.setCookie(key: "uuid", value: "tempUdid" as AnyObject, group: group)
self.setCookie(key: "name", value: "tempName" as AnyObject, group: group)
group.notify(queue: DispatchQueue.main) {
//Create and Load WebView here
let webConfig = (UIApplication.shared.delegate as? AppDelegate)?.webConfig ?? WKWebViewConfiguration()
//create urlRequest
let webView = WKWebView(frame: .zero, configuration: webConfig)
self.webView.load(urlRequest)
}
答案 22 :(得分:0)
显示了针对XHR请求的更好修复here
Swift 4版本:
func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Swift.Void) {
guard
let response = navigationResponse.response as? HTTPURLResponse,
let url = navigationResponse.response.url
else {
decisionHandler(.cancel)
return
}
if let headerFields = response.allHeaderFields as? [String: String] {
let cookies = HTTPCookie.cookies(withResponseHeaderFields: headerFields, for: url)
cookies.forEach { (cookie) in
HTTPCookieStorage.shared.setCookie(cookie)
}
}
decisionHandler(.allow)
}