Explain Cookie management method in iOS App development in detail

  • 2020-06-19 11:46:30
  • OfStack

1. What is a Cookie

Cookie is the user credential information stored locally in the terminal for the purpose of terminal identity. The fields and meanings in Cookie are defined by the server. For example, when the user log in a website, the server will Cookie information back to the terminal, the terminal will save these information, the next one visit this site again, terminal will save Cookie information 1 and sent to the server, the server according to whether effective Cookie information to judge whether the user can be automatically logged in.

2. Two classes managed by Cookie in iOS

In iOS, HTTP network request Cookie management is mainly handled by two classes, one is NSHTTPCookieStorage class, the other is NSHTTPCookie class.

1.NSHTTPCookieStorage

The NSHTTPCookieStorage class adopts a singleton design pattern, where Cookie information is managed for all HTTP requests. The common methods are as follows:

//获取单例对象
+ (NSHTTPCookieStorage *)sharedHTTPCookieStorage;
//所有Cookie数据数组 其中存放NSHTTPCookie对象
@property (nullable , readonly, copy) NSArray<NSHTTPCookie *> *cookies;
//手动设置1条Cookie数据
- (void)setCookie:(NSHTTPCookie *)cookie;
//删除某条Cookie信息
- (void)deleteCookie:(NSHTTPCookie *)cookie;
//删除某个时间后的所有Cookie信息 iOS8后可用
- (nullable NSArray<NSHTTPCookie *> *)cookiesForURL:(NSURL *)URL;
//获取某个特定URL的所有Cookie数据
- (void)removeCookiesSinceDate:(NSDate *)date NS_AVAILABLE(10_10, 8_0);
//为某个特定的URL设置Cookie
- (void)setCookies:(NSArray<NSHTTPCookie *> *)cookies forURL:(nullable NSURL *)URL mainDocumentURL:(nullable NSURL *)mainDocumentURL;
//Cookie数据的接收协议
/*
枚举如下:
typedef NS_ENUM(NSUInteger, NSHTTPCookieAcceptPolicy) {
    NSHTTPCookieAcceptPolicyAlways,//接收所有Cookie信息
    NSHTTPCookieAcceptPolicyNever,//不接收所有Cookie信息
    NSHTTPCookieAcceptPolicyOnlyFromMainDocumentDomain//只接收主文档域的Cookie信息
};
*/
@property NSHTTPCookieAcceptPolicy cookieAcceptPolicy;
Two notifications below the system relate to Cookie administration:

//Cookie数据的接收协议改变时发送的通知
FOUNDATION_EXPORT NSString * const NSHTTPCookieManagerAcceptPolicyChangedNotification;
//管理的Cookie数据发生变化时发送的通知
FOUNDATION_EXPORT NSString * const NSHTTPCookieManagerCookiesChangedNotification;

2.NSHTTPCookie

NSHTTPCookie is the specific HTTP request Cookie data object, where the attribute method is as follows:

//下面两个方法用于对象的创建和初始化 都是通过字典进行键值设置
- (nullable instancetype)initWithProperties:(NSDictionary<NSString *, id> *)properties;
+ (nullable NSHTTPCookie *)cookieWithProperties:(NSDictionary<NSString *, id> *)properties;
//返回Cookie数据中可用于添加HTTP头字段的字典
+ (NSDictionary<NSString *, NSString *> *)requestHeaderFieldsWithCookies:(NSArray<NSHTTPCookie *> *)cookies;
//从指定的响应头和URL地址中解析出Cookie数据
+ (NSArray<NSHTTPCookie *> *)cookiesWithResponseHeaderFields:(NSDictionary<NSString *, NSString *> *)headerFields forURL:(NSURL *)URL;
//Cookie数据中的属性字典
@property (nullable, readonly, copy) NSDictionary<NSString *, id> *properties;
//请求响应的版本
@property (readonly) NSUInteger version;
//请求相应的名称
@property (readonly, copy) NSString *name;
//请求相应的值
@property (readonly, copy) NSString *value;
//过期时间
@property (nullable, readonly, copy) NSDate *expiresDate;
//请求的域名
@property (readonly, copy) NSString *domain;
//请求的路径
@property (readonly, copy) NSString *path;
//是否是安全传输
@property (readonly, getter=isSecure) BOOL secure;
//是否只发送HTTP的服务
@property (readonly, getter=isHTTPOnly) BOOL HTTPOnly;
//响应的文档
@property (nullable, readonly, copy) NSString *comment;
//相应的文档URL
@property (nullable, readonly, copy) NSURL *commentURL;
//服务端口列表
@property (nullable, readonly, copy) NSArray<NSNumber *> *portList;

3. Remove Cookie
Clear all cookie methods:

NSURL *url = [NSURL URLWithString:@"http://www.baidu.com"]; 
    if (url) { 
        NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:url]; 
        for (int i = 0; i < [cookies count]; i++) { 
            NSHTTPCookie *cookie = (NSHTTPCookie *)[cookies objectAtIndex:i]; 
            [[NSHTTPCookieStorage sharedHTTPCookieStorage] deleteCookie:cookie]; 
             
        }  
Clear a particular cookie method:
NSArray * cookArray = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:[NSURL URLWithString:self.loadURL]]; NSString * successCode = @""; for (NSHTTPCookie*cookie in cookArray) { if ([cookie.name isEqualToString:@"cookiename"]) { [[NSHTTPCookieStorage sharedHTTPCookieStorage] deleteCookie:cookie]; } } 

Method to clear a certain url cache:
[[NSURLCache sharedURLCache] removeCachedResponseForRequest:[NSURLRequest requestWithURL:url]]; 

Clear all caching methods:
[[NSURLCache sharedURLCache] removeAllCachedResponses]; 


Related articles: