是否可以使用sharedHTTPCookieStorage为UIWebView手动设置cookie? [英] Is it possible to set a cookie manually using sharedHTTPCookieStorage for a UIWebView?

查看:342
本文介绍了是否可以使用sharedHTTPCookieStorage为UIWebView手动设置cookie?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在iOS应用程序中有Web视图,需要对身份验证cookie进行适当的身份验证。我正在寻找一种在iOS应用程序的webview中设置cookie的方法,而不必发出设置cookie的出站请求,因为我已经在客户端上有auth信息。

I have webviews inside of an iOS application that require an authentication cookie to be properly authenticated. I'm looking for a way to set a cookie inside of an iOS application's webview without having to make an outbound request to set the cookie as I have auth information on the client already.

发布向我们展示了UIWebView Cookie的存储位置。

This post shows us where the UIWebView cookies are stored.

现在我正在加载一个隐藏的Web视图来发出出站请求,但是我不想做出设置简单cookie的外部请求。

Right now I'm loading a hidden web view to make an outbound request but would prefer not to have to make an external request for setting a simple cookie.

推荐答案

是的,你可以这样做。首先,在applicationDidBecomeActive中添加此行

Yes, you can do this. First, in applicationDidBecomeActive add this line

[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookieAcceptPolicy:NSHTTPCookieAcceptPolicyAlways];

cookieAcceptPolicy在各个应用之间共享,可以在您不知情的情况下进行更改,因此您需要确保拥有每次应用运行时所需的接受政策。

The cookieAcceptPolicy is shared across apps and can be changed without your knowledge, so you want to be sure you have the accept policy you need every time your app is running.

然后,设置cookie:

Then, to set the 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。

This cookie has the name testCookie and value someValue123456 and will be sent with any http request to www.example.com.

有关设置cookie的一个重要提示,请在此处查看我的问题!

For one big caveat to setting cookies, please see my question here!

NSHTTPCookieStorage状态未保存在应用程序出口上。那里有任何明确的知识/文件吗?

这篇关于是否可以使用sharedHTTPCookieStorage为UIWebView手动设置cookie?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆