欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

详解iOS App开发中session和coockie的用户数据存储处理

程序员文章站 2023-12-09 13:44:03
nsurlsession 在ios7之后,nsurlsession作为系统推荐使用的http请求框架,在进行前台请求的情况下,nsurlsession与nsurlconn...

nsurlsession
在ios7之后,nsurlsession作为系统推荐使用的http请求框架,在进行前台请求的情况下,nsurlsession与nsurlconnection并无太大差异,对于后台的请求,nsurlsession更加灵活的优势就将展现无遗。
1.nsurlsession集合的类型

nsurlsession类提供3中session类型:

(1)default类型:提供前台请求相关方法,支持配置缓存,身份凭证等。

(2)ephemeral类型:即时的请求类型,不使用缓存,身份凭证等。

(3)background:后台类型,支持在后台完成请求任务。

2.nsurlsession任务的类型

在nsurlsession中添加的请求任务支持3中类型:

(1)数据任务:使用nsdata对象进行数据的发送和获取,一般用于短数据的任务。

(2)下载任务:从文件下载数据,支持后台下载。

(3)上传任务:以文件的形式上传数据,支持后台上传。

3.创建并配置nsurlsession:

通过nsurlsessionconfiguration类对象对nsurlsession进行配置与创建,创建和配nsurlsession的示例代码如下:

    //默认类型的
    nsurlsessionconfiguration * defaultconfiguration = [nsurlsessionconfiguration defaultsessionconfiguration];
    //即时类型的
    nsurlsessionconfiguration * ephemeralconfiguration = [nsurlsessionconfiguration ephemeralsessionconfiguration];
    //后台类型的
    nsurlsessionconfiguration * backgroundconfiguration = [nsurlsessionconfiguration backgroundsessionconfigurationwithidentifier:@"sessionid"];
   
    //创建并设置session
    nsurlsession * defaultsession = [nsurlsession sessionwithconfiguration:defaultconfiguration];
    nsurlsession * ephemeralsession = [nsurlsession sessionwithconfiguration:ephemeralconfiguration];
    nsurlsession * backgroundsession = [nsurlsession sessionwithconfiguration:backgroundconfiguration];
nsurlsessionconfiguration还可以配置如缓存,网络模式等参数

4.使用nsurlsession进行网络请求的两种方式

nsurlsession有两种方式进行网络数据的请求,一种是通过block的方式获取网络数据,一种是通过代理回调的方式获取网络数据。通过block的方式进行请求代码如下:

    //创建session配置对象
    nsurlsessionconfiguration * defaultconfiguration = [nsurlsessionconfiguration defaultsessionconfiguration];
    //创建请求对象
    nsurlrequest * request = [nsurlrequest requestwithurl:[nsurl urlwithstring:@"http://www.baidu.com"]];
    //创建session对象
    nsurlsession * defaultsession = [nsurlsession sessionwithconfiguration:defaultconfiguration];
    //添加任务
    nsurlsessiontask * task= [defaultsession datataskwithrequest:request completionhandler:^(nsdata * _nullable data, nsurlresponse * _nullable response, nserror * _nullable error) {
        nslog(@"%@",data);
    }];
    //开始任务
    [task resume];
使用代理回调的方式进行请求需要遵守如下协议:

@interface viewcontroller ()<nsurlsessiondatadelegate>
@end
将请求代码修改如下:

    nsurlsessionconfiguration * defaultconfiguration = [nsurlsessionconfiguration defaultsessionconfiguration];
    nsurlrequest * request = [nsurlrequest requestwithurl:[nsurl urlwithstring:@"http://www.baidu.com"]];
    nsurlsession * defaultsession = [nsurlsession sessionwithconfiguration:defaultconfiguration delegate:self delegatequeue:[nsoperationqueue mainqueue]];

    nsurlsessiontask * task= [defaultsession datataskwithrequest:request];
    [task resume];
实现代理方法如下:

//开始接受数据
-(void)urlsession:(nsurlsession *)session datatask:(nsurlsessiondatatask *)datatask didreceivedata:(nsdata *)data{
    nslog(@"=======%@",data);
}
//接受数据结束
-(void)urlsession:(nsurlsession *)session task:(nsurlsessiontask *)task didcompletewitherror:(nserror *)error{
    nslog(@"完成:error%@",error);
}
5.进行后台下载任务

nsurlsession最大的优势在于其后台下载的灵活性,使用如下的代码进行后台数据下载:

 nsurlsessionconfiguration * backgroundconfiguration = [nsurlsessionconfiguration backgroundsessionconfigurationwithidentifier:@"com.zyprosoft.backgroundsession"];
    nsurlrequest * request = [nsurlrequest requestwithurl:[nsurl urlwithstring:@"http://www.baidu.com"]];
    nsurlsession *  backgroundsession   = [nsurlsession sessionwithconfiguration:backgroundconfiguration delegate:self delegatequeue:nil];
    [[backgroundsession downloadtaskwithrequest:request]resume];
在下面的回调方法中可以进行下载进度的监听:

- (void)urlsession:(nsurlsession *)session downloadtask:(nsurlsessiondownloadtask *)downloadtask didwritedata:(int64_t)byteswritten totalbyteswritten:(int64_t)totalbyteswritten totalbytesexpectedtowrite:(int64_t)totalbytesexpectedtowrite
{
    nslog(@"######");
}
如果在下载过程中点击home键使应用程序进入后台,nsurlsession的相关代理方法将不再被回调,但是下载任务依然在进行,当后台下载完成后会与appdelegate进行交互,会调用appdelegate中的如下方法:

-(void)application:(uiapplication *)application handleeventsforbackgroundurlsession:(nsstring *)identifier completionhandler:(void (^)())completionhandler{
    nslog(@"1111");
}
之后应用程序在后台会调用nsurlsesstion代理的如下方法来通知下载结果:

//此方法无论成功失败都会调用
-(void)urlsession:(nsurlsession *)session task:(nsurlsessiontask *)task didcompletewitherror:(nserror *)error{
    nslog(@"完成:error%@",error);
}
//此方法只有下载成功才会调用 文件放在location位置
-(void)urlsession:(nsurlsession *)session downloadtask:(nsurlsessiondownloadtask *)downloadtask didfinishdownloadingtourl:(nsurl *)location{
   
}
最后将调用nsurlsesstion的如下方法:

-(void)urlsessiondidfinisheventsforbackgroundurlsession:(nsurlsession *)session
{
   
    nslog(@"all tasks are finished");
   
}

cookie

cookie是网站为了便是终端身份,保存在终端本地的用户凭证信息。cookie中的字段与意义由服务端进行定义。例如,当用户在某个网站进行了登录操作后,服务端会将cookie信息返回给终端,终端会将这些信息进行保存,在下一次再次访问这个网站时,终端会将保存的cookie信息一并发送到服务端,服务端根据cookie信息是否有效来判断此用户是否可以自动登录。

ios中进行cookie管理的两个类:

ios中进行http网络请求cookie管理主要由两个类负责,一个类是nshttpcookiestorage类,一个是nshttpcookie类。

1.nshttpcookiestorage

nshttpcookiestorage类采用单例的设计模式,其中管理着所有http请求的cookie信息,常用方法如下:

//获取单例对象
+ (nshttpcookiestorage *)sharedhttpcookiestorage;
//所有cookie数据数组 其中存放nshttpcookie对象
@property (nullable , readonly, copy) nsarray<nshttpcookie *> *cookies;
//手动设置一条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;
系统下面的两个通知与cookie管理有关:

//cookie数据的接收协议改变时发送的通知
foundation_export nsstring * const nshttpcookiemanageracceptpolicychangednotification;
//管理的cookie数据发生变化时发送的通知
foundation_export nsstring * const nshttpcookiemanagercookieschangednotification;

2.nshttpcookie

nshttpcookie是具体的http请求cookie数据对象,其中属性方法如下:

//下面两个方法用于对象的创建和初始化 都是通过字典进行键值设置
- (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;