Backend Development 10 min read

Understanding Cookies: Types, Usage, and iOS Integration

This article explains what cookies and sessions are, their types and attributes, demonstrates how they control language preferences on a website, and provides practical iOS examples using NSHTTPCookie, AFNetworking, and NSURLSession to send and manage cookies in network requests.

360 Zhihui Cloud Developer
360 Zhihui Cloud Developer
360 Zhihui Cloud Developer
Understanding Cookies: Types, Usage, and iOS Integration

1. What is a Cookie

Cookie (or Cookies) refers to data stored on a user's device by a website to identify the user and track sessions, usually encrypted.

2. What is a Session

Because HTTP is a stateless protocol, the server uses a session mechanism to recognize a specific user.

3. Uses of Cookies

Using jianshu.com as an example, when the browser first accesses the site it defaults to Simplified Chinese. Setting the language to Traditional Chinese creates a cookie (local=zh‑TW) that persists after the browser is closed, so the site continues to display Traditional Chinese. Without cookies, the language choice would be lost after closing the browser.

4. Types of Cookies

According to the HTTP Guide, cookies are divided into two categories: session cookies and persistent cookies. Session cookies are temporary and are deleted when the browser closes. Persistent cookies have a longer lifespan, are stored on disk, and survive browser restarts; they are typically used to maintain configuration or login information.

5. Example of Cookies on jianshu.com

Persistent cookie example:

expires: Tue, 09 Apr 2019 13:31:57 -0000

domain: .jianshu.com

path: /

Secure: YES

HttpOnly: true

Session cookie example:

local: zh‑CN (display Simplified Chinese)

6. Cookie Workflow

1) The first visit creates a session on the server and the browser shows Simplified Chinese. 2) Changing the language to Traditional Chinese sets a cookie (local=zh‑TW) and updates the server‑side session. 3) Closing the browser may delete the session, but the server can still retrieve the language preference from the stored cookie when the browser is reopened, causing the site to continue displaying Traditional Chinese.

7. Cookie Attributes

Domain – the domain to which the cookie will be sent.

Path – the URL path prefix for which the cookie is valid.

Secure – send the cookie only over HTTPS.

Expires – expiration time expressed as seconds since 1 Jan 1970 UTC.

Name – the cookie’s name.

Value – the cookie’s value.

8. iOS NSHTTPCookie

Common properties:

NSHTTPCookieDomain – cookie domain.

NSHTTPCookiePath – cookie path.

NSHTTPCookiePort – list of ports.

NSHTTPCookieName – cookie name.

NSHTTPCookieValue – cookie value.

NSHTTPCookieVersion – cookie version.

NSHTTPCookieExpires – expiration date.

NSHTTPCookieDiscard – whether to discard at session end.

HTTPOnly – prevent JavaScript access.

NSHTTPCookieSecure – send only over HTTPS.

properties – dictionary of all attributes.

NSHTTPCookieComment – comment text.

NSHTTPCookieCommentURL – comment URL.

NSHTTPCookieAcceptPolicy – policy for storing cookies (Always, Never, OnlyFromMainDocumentDomain).

9. Using Cookies with AFNetworking

Set the cookie header manually on the request serializer and perform a GET request.

<code>NSString *urlString = @"https://juejin.im");
AFHTTPSessionManager *sessionManager = [AFHTTPSessionManager manager];
sessionManager.responseSerializer = [AFHTTPResponseSerializer serializer];
[sessionManager.requestSerializer setValue:@"QiShareNameAFN=QiShareValueAFN;QiShareTokenAFN=QiShareTokenValueAFN" forHTTPHeaderField:@"cookie"];
[sessionManager GET:urlString parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
    // handle success
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
    // handle failure
}];
</code>

10. Using Cookies with NSURLSession

Construct the request, set the cookie header, create a data task, and resume it.

<code>NSURL *url = [NSURL URLWithString:@"https://www.jianshu.com"];
NSMutableURLRequest *mRequest = [NSMutableURLRequest requestWithURL:url];
mRequest.HTTPMethod = @"GET";
[mRequest setValue:@"QiShareName=QiShareValue;QiShareToken=QiShareTokenValue" forHTTPHeaderField:@"cookie"];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:mRequest completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
    // handle response
}];
[dataTask resume];
</code>

Images illustrating the cookies on jianshu.com and the network request results:

Cookies on jianshu.com
Cookies on jianshu.com
AFNetworking request result
AFNetworking request result
NSURLSession request result
NSURLSession request result
iOSweb developmentNetworkingcookiesAFNetworkingsessionNSURLSession
360 Zhihui Cloud Developer
Written by

360 Zhihui Cloud Developer

360 Zhihui Cloud is an enterprise open service platform that aims to "aggregate data value and empower an intelligent future," leveraging 360's extensive product and technology resources to deliver platform services to customers.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.