详细解析几个和网络请求有关的类(十五) —— NSHTTPCookieStorage(一)

版本记录

版本号 时间
V1.0 2018.03.15

前言

我们做APP发起网络请求,一般都是使用框架,这些框架的底层也都是苹果的API,接下来几篇就一起来看一下和网络有关的几个类。感兴趣的可以看上面几篇文章。
1. 详细解析几个和网络请求有关的类 (一) —— NSURLSession
2. 详细解析几个和网络请求有关的类(二) —— NSURLRequest和NSMutableURLRequest
3. 详细解析几个和网络请求有关的类(三) —— NSURLConnection
4. 详细解析几个和网络请求有关的类(四) —— NSURLSession和NSURLConnection的区别
5. 详细解析几个和网络请求有关的类(五) —— 关于NSURL加载系统(一)
6. 详细解析几个和网络请求有关的类(六) —— 使用NSURLSession(二)
7. 详细解析几个和网络请求有关的类(七) —— URL数据的编码和解码(三)
8. 详细解析几个和网络请求有关的类(八) —— 处理重定向和其他请求更改(四)
9. 详细解析几个和网络请求有关的类(九) —— 身份验证挑战和TLS链验证(五)
10. 详细解析几个和网络请求有关的类(十) —— 理解获取缓存(六)
11. 详细解析几个和网络请求有关的类(十一) —— Cookies和自定义协议(七)
12. 详细解析几个和网络请求有关的类(十二) —— URL Session的生命周期(八)
13. 详细解析几个和网络请求有关的类(十三) —— NSURLResponse(一)
14. 详细解析几个和网络请求有关的类(十四) —— NSHTTPCookie(一)

回顾

上一篇讲述关于NSHTTPCookie,下面这篇我们就主要看一下NSHTTPCookieStorage


基本信息

首先我们看一下该类的基本信息。

1. Overview

管理cookie存储的单例对象(共享实例)。

每个cookie都由NSHTTPCookie类的实例表示。 通常,Cookie在所有应用程序之间共享,并跨越进程边界保持同步。 Session cookie(cookie对象的sessionOnly方法返回true)对于单个进程是本地的,不共享。

iOS Note:在iOS中cookie在程序之间是不共享的。

注意:对cookie接受策略所做的更改会影响使用cookie存储的所有当前正在运行的应用程序。

当你访问一个网站时,NSURLRequest都会帮你主动记录下来你访问的站点设置的Cookie,如果 Cookie 存在的话,会把这些信息放在 NSHTTPCookieStorage 容器中共享,当你下次再访问这个站点时,NSURLRequest会拿着上次保存下来了的Cookie继续去请求。

NSHTTPCookieStorage 实现了一个管理Cookie的单例对象(只有一个实例),每个Cookie都是NSHTTPCookie类的实例,作为一个规则,Cookie在所有应用之间共享并在不同进程之间保持同步。Session Cookie(一个isSessionOnly方法返回YES的Cookie)只能在单一进程中使用。

2. Thread Safety - 线程安全

macOS 10.9及更高版本和iOS 7及更高版本中,NSHTTPCookieStorage是线程安全的。


Topics

1. Creating and Initializing a Cookie Storage Object - 创建和初始化Cookie Storage对象

  • - initWithStorageLocation:
    • 返回一个具有给定文件系统位置的初始化NSHTTPCookieStorage对象,以将Cookie信息存储在磁盘上。

2. Getting the Shared Cookie Storage Object - 获取共享的Cookie Storage对象

3. Getting and Setting the Cookie Accept Policy - 获取和设置Cookie Accept Policy

4. Adding and Removing Cookies - 增加和移除Cookie

5. Retrieving Cookies - 检索Cookies

6. Constants

7. Notifications


API 文档

NSHTTPCookieStorage分类

接下来我们看一下API文档,我在里面增加了注释。

#import <Foundation/NSObject.h>
#import <Foundation/NSNotification.h>

@class NSArray<ObjectType>;
@class NSHTTPCookie;
@class NSURL;
@class NSDate;
@class NSURLSessionTask;
@class NSSortDescriptor;

NS_ASSUME_NONNULL_BEGIN

/*!
    @enum NSHTTPCookieAcceptPolicy
    @abstract Values for the different cookie accept policies
    @constant NSHTTPCookieAcceptPolicyAlways Accept all cookies
    @constant NSHTTPCookieAcceptPolicyNever Reject all cookies
    @constant NSHTTPCookieAcceptPolicyOnlyFromMainDocumentDomain Accept cookies
    only from the main document domain
*/
// 这里是不同cookie接受策略的值
typedef NS_ENUM(NSUInteger, NSHTTPCookieAcceptPolicy) {
    // 接受所有的cookie
    NSHTTPCookieAcceptPolicyAlways,

    // 拒绝所有的cookie
    NSHTTPCookieAcceptPolicyNever,
    
    //只接受来自主文件域的cookie
    NSHTTPCookieAcceptPolicyOnlyFromMainDocumentDomain
};


@class NSHTTPCookieStorageInternal;

/*!
    @class NSHTTPCookieStorage 
    @discussion NSHTTPCookieStorage implements a singleton object (shared
    instance) which manages the shared cookie store.  It has methods
    to allow clients to set and remove cookies, and get the current
    set of cookies.  It also has convenience methods to parse and
    generate cookie-related HTTP header fields.
*/
// NSHTTPCookieStorage实现了一个管理共享cookie存储的单例对象(共享实例)。 它具有允许客户设置和删除Cookie的方法,并获得当前的一组Cookie。 它还具有解析和生成与cookie相关的HTTP头字段的便捷方法。

@interface NSHTTPCookieStorage : NSObject
{
    @private
    NSHTTPCookieStorageInternal *_internal;
}

/*!
    @property sharedHTTPCookieStorage
    @abstract Get the shared cookie storage in the default location.
    @result The shared cookie storage
    @discussion Starting in OS X 10.11, each app has its own sharedHTTPCookieStorage singleton, 
    which will not be shared with other applications.
*/
// 获取在默认位置的共享cookie storage。从OS X 10.11开始,
// 每一个app都有自己的sharedHTTPCookieStorage单例,不会和其他程序分享。

@property(class, readonly, strong) NSHTTPCookieStorage *sharedHTTPCookieStorage;

/*!
    @method sharedCookieStorageForGroupContainerIdentifier:
    @abstract Get the cookie storage for the container associated with the specified application group identifier
    @param identifier The application group identifier
    @result A cookie storage with a persistent store in the application group container
    @discussion By default, applications and associated app extensions have different data containers, which means
    that the sharedHTTPCookieStorage singleton will refer to different persistent cookie stores in an application and
    any app extensions that it contains. This method allows clients to create a persistent cookie storage that can be
    shared among all applications and extensions with access to the same application group. Subsequent calls to this
    method with the same identifier will return the same cookie storage instance.
 */
// 获取与指定应用程序组标识符关联的容器的Cookie存储。
// identifier:应用程序组标识符
// result:在应用程序组容器中具有持久性存储的Cookie存储
// 默认情况下,应用程序和关联的应用程序扩展具有不同的数据容器,
// 这意味着sharedHTTPCookieStorage单例将引用应用程序中的不同持久性cookie
// 存储以及它包含的任何应用程序扩展。 此方法允许客户端创建持久性cookie存储,
// 可以在所有应用程序和扩展中共享,并访问相同的应用程序组。 随后使用相同标识符调用
// 此方法将返回相同的cookie存储实例。

+ (NSHTTPCookieStorage *)sharedCookieStorageForGroupContainerIdentifier:(NSString *)identifier API_AVAILABLE(macos(10.11), ios(9.0), watchos(2.0), tvos(9.0));

/*!
    @abstract Get all the cookies
    @result An NSArray of NSHTTPCookies
*/
// 获取所有的cookies

@property (nullable , readonly, copy) NSArray<NSHTTPCookie *> *cookies;

/*!
    @method setCookie:
    @abstract Set a cookie
    @discussion The cookie will override an existing cookie with the
    same name, domain and path, if any.
*/
// 设置cookie,该cookie将覆盖具有相同名称,域和路径的现有cookie,如果有的话。

- (void)setCookie:(NSHTTPCookie *)cookie;

/*!
    @method deleteCookie:
    @abstract Delete the specified cookie
*/
// 删除指定的cookie
- (void)deleteCookie:(NSHTTPCookie *)cookie;

/*!
 @method removeCookiesSince:
 @abstract Delete all cookies from the cookie storage since the provided date.
 */
// 删除指定日期cookie storage中所有的cookie

- (void)removeCookiesSinceDate:(NSDate *)date API_AVAILABLE(macos(10.10), ios(8.0), watchos(2.0), tvos(9.0));

/*!
    @method cookiesForURL:
    @abstract Returns an array of cookies to send to the given URL.
    @param URL The URL for which to get cookies.
    @result an NSArray of NSHTTPCookie objects.
    @discussion The cookie manager examines the cookies it stores and
    includes those which should be sent to the given URL. You can use
    <tt>+[NSCookie requestHeaderFieldsWithCookies:]</tt> to turn this array
    into a set of header fields to add to a request.
*/
// 返回要发送到给定URL的Cookie数组。
// Cookie管理器检查它存储的cookie,其中包含应发送到给定URL的cookie。 
// 您可以使用<tt> + [NSCookie requestHeaderFieldsWithCookies:] </ tt>
// 将此数组转换为一组头字段以添加到请求中

- (nullable NSArray<NSHTTPCookie *> *)cookiesForURL:(NSURL *)URL;

/*!
    @method setCookies:forURL:mainDocumentURL:
    @abstract Adds an array cookies to the cookie store, following the
    cookie accept policy.
    @param cookies The cookies to set.
    @param URL The URL from which the cookies were sent.
    @param mainDocumentURL The main document URL to be used as a base for the "same
    domain as main document" policy.
    @discussion For mainDocumentURL, the caller should pass the URL for
    an appropriate main document, if known. For example, when loading
    a web page, the URL of the main html document for the top-level
    frame should be passed. To save cookies based on a set of response
    headers, you can use <tt>+[NSCookie
    cookiesWithResponseHeaderFields:forURL:]</tt> on a header field
    dictionary and then use this method to store the resulting cookies
    in accordance with policy settings.
*/
// 将cookie数组添加到cookie store,遵守cookie 接受策略。 
// mainDocumentURL: 主要文档URL用作“与主文档相同的域”策略的基础
// 对于mainDocumentURL,调用者应该传递适当主文档的URL(如果知道)。 
// 例如,在加载网页时,应传递顶层框架的主要html文档的URL。 
// 要根据一组响应头保存cookie,您可以在头字段字典中使用<tt> + [NSCookie cookiesWithResponseHeaderFields:forURL:] </ tt>,
// 然后使用此方法根据策略设置存储生成的cookie。

- (void)setCookies:(NSArray<NSHTTPCookie *> *)cookies forURL:(nullable NSURL *)URL mainDocumentURL:(nullable NSURL *)mainDocumentURL;

/*!
    @abstract The cookie accept policy preference of the
    receiver.
*/
// 接收者的cookie可接受策略。

@property NSHTTPCookieAcceptPolicy cookieAcceptPolicy;

/*!
  @method sortedCookiesUsingDescriptors:
  @abstract Returns an array of all cookies in the store, sorted according to the key value and sorting direction of the NSSortDescriptors specified in the parameter.
  @param sortOrder an array of NSSortDescriptors which represent the preferred sort order of the resulting array.
  @discussion proper sorting of cookies may require extensive string conversion, which can be avoided by allowing the system to perform the sorting.  This API is to be preferred over the more generic -[NSHTTPCookieStorage cookies] API, if sorting is going to be performed.
*/
// 返回存储区中所有Cookie的数组,根据参数中指定的NSSortDescriptors的键值和排序方向进行排序
// sortOrder:一个NSSortDescriptors数组,表示结果数组的首选排序顺序
// 恰当地分类cookies可能需要大量的字符串转换,这可以通过允许系统执行分类来避免。 
// 如果要执行排序,则此API比更通用的[NSHTTPCookieStorage cookie] API更受欢迎

- (NSArray<NSHTTPCookie *> *)sortedCookiesUsingDescriptors:(NSArray<NSSortDescriptor *> *) sortOrder API_AVAILABLE(macos(10.7), ios(5.0), watchos(2.0), tvos(9.0));

@end

NSHTTPCookieStorage分类NSURLSessionTaskAdditions

这个是针对给定任务的NSHTTPCookieStorage分类

@interface NSHTTPCookieStorage (NSURLSessionTaskAdditions)

// 根据给定的task存储Cookie
- (void)storeCookies:(NSArray<NSHTTPCookie *> *)cookies forTask:(NSURLSessionTask *)task API_AVAILABLE(macos(10.10), ios(8.0), watchos(2.0), tvos(9.0));

// 获取指定任务的Cookie,并处理完成回调
- (void)getCookiesForTask:(NSURLSessionTask *)task completionHandler:(void (^) (NSArray<NSHTTPCookie *> * _Nullable cookies))completionHandler API_AVAILABLE(macos(10.10), ios(8.0), watchos(2.0), tvos(9.0));

@end

/*!
    @const NSHTTPCookieManagerAcceptPolicyChangedNotification
    @discussion Name of notification that should be posted to the
    distributed notification center whenever the accept cookies
    preference is changed
*/
FOUNDATION_EXPORT NSNotificationName const NSHTTPCookieManagerAcceptPolicyChangedNotification;

/*!
    @const NSHTTPCookieManagerCookiesChangedNotification
    @abstract Notification sent when the set of cookies changes
*/
FOUNDATION_EXPORT NSNotificationName const NSHTTPCookieManagerCookiesChangedNotification;

NS_ASSUME_NONNULL_END

后记

本篇主要讲述了NSHTTPCookieStorage这个类的使用,喜欢的给个赞和关注哈~~~~

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,651评论 6 501
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,468评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,931评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,218评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,234评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,198评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,084评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,926评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,341评论 1 311
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,563评论 2 333
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,731评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,430评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,036评论 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,676评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,829评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,743评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,629评论 2 354

推荐阅读更多精彩内容