无法使用document.cookie在UIWebview浏览器中读取cookie

fen*_*yer 5 javascript cookies ajax uiwebview ios

我有一个iOS应用程序,我在webview中加载html内容.html是登录页面,其中用户凭证通过ajax发送到服务器,并且接收到认证成功/失败响应.现在,响应包含一个cookie(在Set-Cookie标题字段中),我可以在Objective-C端捕获,就像这样,

NSDictionary* headers = [(NSHTTPURLResponse *)response allHeaderFields]; 
NSString *strCookies = [headers valueForKey:@"Set-Cookie"]; 
NSLog(@"cookies -> %@", strCookies);
Run Code Online (Sandbox Code Playgroud)

同样的响应还包含responseText我在浏览器中使用的响应:

Ajax("/login", "POST", { onsuccess : function(response){ 
       /* Do HTML stuff with response */ }  
});
Run Code Online (Sandbox Code Playgroud)

现在我需要cookie来进一步的ajax请求(在登录页面之后).但是,cookie未在webview浏览器中设置.寻找document.cookie返回一个空字符串.我可以使用打印所有响应头xhr.getAllResponseHeaders()但我无法访问Set-Cookiexhr对象中的字段.

如何在webview中设置cookie?或者我别无选择,只能通过Obj-C发出所有ajax请求?

eli*_*o.d 2

您可以在发送到 webview 的请求中设置 cookie。

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:yourURL];
[request setValue:yourCookie forHTTPHeaderField:@"Cookie"];
Run Code Online (Sandbox Code Playgroud)

这可以在 UIWebview 委托 shouldStartLoadWithRequest 中完成