Как я понял.Из одного моего старого проекта: (извините за Objective C. Его легко конвертировать в Swift)
-(void)saveCookies:(NSString*)user_id{
NSMutableArray *theCookies = [NSMutableArray new];
for(NSHTTPCookie *cookie in [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]) {
[theCookies addObject:cookie];
}
if (theCookies.count>0){
NSData *cd = [NSKeyedArchiver archivedDataWithRootObject:theCookies];
NSString *cookiesFilesPath = [appDelegate cookPathForUser:user_id]; // Here your path to file (or you can store it anywhere)
[[NSFileManager defaultManager] createFileAtPath:cookiesFilesPath contents:[NSData data] attributes:nil];
[cd writeToFile:cookiesFilesPath atomically:YES];
}
}
-(NSArray*)cookiesForUser:(NSString*)user_id{
NSData *cookiesData = [NSData dataWithContentsOfFile:[appDelegate cookPathForUser:user_id]];
NSArray *cookies = [NSKeyedUnarchiver unarchiveObjectWithData:cookiesData];
return cookies;
}
-(void)resetCookies {
[[NSURLCache sharedURLCache] removeAllCachedResponses];
for(NSHTTPCookie *cookie in [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]) {
[[NSHTTPCookieStorage sharedHTTPCookieStorage] deleteCookie:cookie];
}
}
- (void)applyCookies:(NSArray*)cookies {
for (int i = 0; i<cookies.count; i++){
NSHTTPCookie *cookie = [cookies objectAtIndex:i];
[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
}
}
- (void)addCookies:(NSArray *)cookies forRequest:(NSMutableURLRequest *)request
{
if ([cookies count] > 0)
{
NSHTTPCookie *cookie;
NSString *cookieHeader = nil;
for (cookie in cookies)
{
if (!cookieHeader)
{
cookieHeader = [NSString stringWithFormat: @"%@=%@",[cookie name],[cookie value]];
}
else
{
cookieHeader = [NSString stringWithFormat: @"%@; %@=%@",cookieHeader,[cookie name],[cookie value]];
}
}
if (cookieHeader)
{
[request setValue:cookieHeader forHTTPHeaderField:@"Cookie"];
}
}
}