- 最近有个问题困扰了我一段时间,就是登陆之后的cookie要保存下来,在后面的接口中还要把登陆的cookie返回给后台。在网上看了一些讲解,结合实际项目接口。最近还是让我给解决了。
废话不多说,直接附上代码
//登陆的时候拿到cookie,用偏好设置存到本地
[manager POST:url parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL: [NSURL URLWithString:url]];
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:cookies];
[[NSUserDefaults standardUserDefaults] setObject:data forKey:url];
//NSLog(@"%@", responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"%@",error);
}];
//在调用其他接口时需要把cookie传给后台,也就是设置cookie的过程
NSData *cookiesdata = [[NSUserDefaults standardUserDefaults] objectForKey:url];//url和登陆时传的url 是同一个
if([cookiesdata length]) {
NSArray *cookies = [NSKeyedUnarchiver unarchiveObjectWithData:cookiesdata];
NSHTTPCookie *cookie;
for (cookie in cookies) {
[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
}
}
网友评论