我在iOS应用程序中有一些webviews,它们需要身份验证cookie才能正确地进行身份验证。我正在寻找一种在iOS应用程序的webview中设置cookie的方法,而不必发出设置cookie的出站请求,因为我已经在客户端上获得了身份验证信息。
此post向我们显示UIWebView cookies的存储位置。
现在,我正在加载一个隐藏的web视图来发出一个出站请求,但我不希望必须发出一个外部请求来设置一个简单的cookie。
发布于 2011-05-11 03:08:20
是的,你可以做到。首先,在applicationDidBecomeActive中添加以下行
[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookieAcceptPolicy:NSHTTPCookieAcceptPolicyAlways];
cookieAcceptPolicy是在应用程序之间共享的,并且可以在您不知情的情况下更改,因此您希望确保每次运行应用程序时都具有所需的接受策略。
然后,设置cookie:
NSMutableDictionary *cookieProperties = [NSMutableDictionary dictionary];
[cookieProperties setObject:@"testCookie" forKey:NSHTTPCookieName];
[cookieProperties setObject:@"someValue123456" forKey:NSHTTPCookieValue];
[cookieProperties setObject:@"www.example.com" forKey:NSHTTPCookieDomain];
[cookieProperties setObject:@"www.example.com" forKey:NSHTTPCookieOriginURL];
[cookieProperties setObject:@"/" forKey:NSHTTPCookiePath];
[cookieProperties setObject:@"0" forKey:NSHTTPCookieVersion];
// set expiration to one month from now or any NSDate of your choosing
// this makes the cookie sessionless and it will persist across web sessions and app launches
/// if you want the cookie to be destroyed when your app exits, don't set this
[cookieProperties setObject:[[NSDate date] dateByAddingTimeInterval:2629743] forKey:NSHTTPCookieExpires];
NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:cookieProperties];
[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
此cookie的名称为testCookie,值为someValue123456,并将随任何http请求一起发送到www.example.com。
有关设置cookie的一个重要警告,请参阅我的问题!
NSHTTPCookieStorage state not saved on app exit. Any definitive knowledge/documentation out there?
发布于 2017-04-26 01:15:27
在Swift 3中,所有的键都包装在HTTPCookiePropertyKey
结构中:
let cookieProperties: [HTTPCookiePropertyKey : Any] = [.name : "name",
.value : "value",
.domain : "www.example.com",
.originURL : "www.example.com",
.path : "/",
.version : "0",
.expires : Date().addingTimeInterval(2629743)
]
if let cookie = HTTPCookie(properties: cookieProperties) {
HTTPCookieStorage.shared.setCookie(cookie)
}
发布于 2016-11-24 21:15:26
需要绕过iOS 10引入的对cookies的限制,这使得它们对不同的进程不可见。
这意味着在具有多处理能力的设备上,webview是一个与您的应用程序不同的进程,这意味着您的" app“会话不再自动传输到webview。
因此,在essense中,你需要这样做(即使是之前的帖子,它在iOS10之前是自动工作的)。
https://stackoverflow.com/questions/5954382
复制相似问题