SoFunction
Updated on 2025-04-11

One article to get iOS cookie access

Introduction to Cookies

Cookies are a mechanism for storing server status on the client. Web servers can set cookies through Set-Cookies or Set-Cookie2 HTTP headers.

Cookies can be divided into two categories: session cookies and persistent cookies. Session cookies are temporary cookies. Cookies will be deleted when the current session ends (browser exits). The persistent cookie will be stored on the user's hard drive, the browser exits, and then the cookie will still exist after restarting. The difference between session cookies and persistent cookies is the expiration time. If the Discard parameter is set (Cookie Version 1) or the expiration time is not set (Expires (Cookie Version 0) or Max-Age (Cookie Version 1) is set, then this cookie is a session cookie.

There are two versions of cookies, one is version 0 (Netscape Cookies) and version 1 (RFC 2965). Currently, most servers use cookies 0.

For details about cookies, please refer to the relevant chapters of the "Authoritative HTTP Guide".

introduction

In order to quickly release an app, some companies often use UINavigationController+WebView or NavigationController+UITabbarVC+WebView. This inevitably requires using cookies to interact with Html5. The following is a description of how to add cookies in several common scenarios:

1. UIWebView:

// Methods for storing cookies in factory class+ (void)saveCookies {
 // Create a variable dictionary to store cookies NSMutableDictionary *fromappDict = [NSMutableDictionary dictionary];
 [fromappDict setObject:@"fromapp" forKey:NSHTTPCookieName];
 [fromappDict setObject:@"ios" forKey:NSHTTPCookieValue];
 // kDomain is the company app website [fromappDict setObject:kDomain forKey:NSHTTPCookieDomain];
 [fromappDict setObject:kDomain forKey:NSHTTPCookieOriginURL];
 [fromappDict setObject:@"/" forKey:NSHTTPCookiePath];
 [fromappDict setObject:@"0" forKey:NSHTTPCookieVersion];
 // Convert variable dictionary to cookies NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:fromappDict];
 // Get cookieStorage NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage]
 //Storage cookies [cookieStorage setCookie:cookie];
}

UIWebView is used for a long time. As long as the corresponding cookie is set in the cookieStorage, it will be automatically brought with you every time;

However, this disadvantage is that as the interaction with H5 increases, cookies occupy more and more space. Each interaction involves a large number of cookies, which not only increases server-side pressure, but also wastes user traffic. For example, every interaction contains 5kb cookie content, but only two or three hundred bytes are used.

2. WKWebView

Compared with UIWebView:

  • The speed is twice as fast, but the memory is reduced to half as it was;
  • Cookies are no longer automatically carried and need to be set manually;
  • The interaction is smoother. For example, the four tabBars at the bottom of the app are also web pages. If you click under UIWebView, the entire H5 page will flash white, but if you click under WKWebView, the four tabBar effects are more similar to the native app effects, and there will be no flash white.
  • Added and deleted some proxy methods to make it more convenient to conduct protocol interception and progress bar display

1. Store it in WKUserScript when creating it to add cookies

 WKWebViewConfiguration *webConfig = [[WKWebViewConfiguration alloc] init];
 // Set preferences  = [[WKPreferences alloc] init];
 // Default is 0  = 10;
 // By default, YES is considered  = YES;
 // Default is NO on iOS, which means it cannot be opened automatically through the window = NO; // web content processing pool  = [[WKProcessPool alloc] init];
 // Splice all cookies in the form = 'key=value'; #warning However, the single quotes here must be paid attention to the English word, don't ask me why I told you this (manual smile) NSString *cookieValue = @" = 'fromapp=ios'; = 'channel=appstore';"; 
 // Add a cookie to h5 to identify it, indicating that the address is opened on the ios side WKUserContentController* userContentController = ;
 WKUserScript * cookieScript = [[WKUserScript alloc]
         initWithSource: cookieValue         injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];
 [userContentController addUserScript:cookieScript];
  = userContentController;
 WKWebView *wkWebView = [[WKWebView alloc] initWithFrame:frame configuration:webConfig];
  = wkWebView;
  = wkWebView;

2. Add cookies when loading a certain URL

If WKWebView needs to add cookies when loading the url, you need to manually get all cookies in the current NSHTTPCookieStorage, and then put the cookies in the NSMutableURLRequest request header

- (void)loadRequestWithUrlString:(NSString *)urlString { 
 // Get the returned cookie here NSMutableDictionary *cookieDic = [NSMutableDictionary dictionary]; 
 NSMutableString *cookieValue = [NSMutableString stringWithFormat:@""];
 NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage]; 
 for (NSHTTPCookie *cookie in [cookieJar cookies]) {
  [cookieDic setObject: forKey:];
 } 
 // Repeat cookies, put them in the dictionary for deduplication, and then splice them for (NSString *key in cookieDic) {
  NSString *appendString = [NSString stringWithFormat:@"%@=%@;", key, [cookieDic valueForKey:key]];
  [cookieValue appendString:appendString];
 }
 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]];
 [request addValue:cookieValue forHTTPHeaderField:@"Cookie"];
 [self loadRequest:request];
}

3、AFNetworking

AFNetworkingaccesscookieIt's more common,Don't say much,It's all in the code
 // Get AFHTTPRequestOperationManager AFHTTPRequestOperationManager *operationManager = [AFHTTPRequestOperationManager manager]; 
 // Create a variable dictionary for storing cookies NSMutableDictionary *cookieDic = [NSMutableDictionary dictionary]; 
 // Store newly added cookies #warning The single cookie is fine, but the author spliced ​​a value containing 6 device information in the factory method, and finally forgot to add a semicolon, and the test did not test it out. #warning Because it does not affect the function, the cookies behind it will be automatically spliced, and the H5 side cannot be identified, which may cause major accidents (involving finance.). I hope later generations will see it and make preparations in advance (just this pit, you have to give me a thumbs up) NSMutableString *cookieValue = [NSMutableString stringWithFormat:@"fromapp=ios;"];
 // Get NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage]; 
 for (NSHTTPCookie *cookie in [cookieJar cookies]) {
  [cookieDic setObject: forKey:];
 } 
 // Repeat cookies, put them in the dictionary to deduplicate them, and then splice them for (NSString *key in cookieDic) {
  NSString *appendString = [NSString stringWithFormat:@"%@=%@;", key, [cookieDic valueForKey:key]];
  [cookieValue appendString:appendString];
 }
 // Save the cookie in the request header [ setValue:cookieValue forHTTPHeaderField:@"Cookie"]; 
 // Splice URL address NSString *urlStr = [NSString stringWithFormat:@"%@%@", kHostIP, kPath]; 
 // Set parameter dictionary NSDictionary *paraDict = @{
         @"key" : value
         };
 // Send a request and process the result [operationManager POST:urlStr parameters:paraDict success:^(AFHTTPRequestOperation * _Nonnull operation, id _Nonnull responseObject) {  
   NSLog(@"responseObject-->%@", responseObject);  
 } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {

   NSLog(@"error-->%@", error);
 }];

Summarize

The above is the entire content of this article. I hope that the content of this article has a certain reference value for everyone's study or work. If you have any questions, you can leave a message to communicate. Thank you for your support.