This article describes how to use cookies in iOS development ASIHTTPRequest, including persistent cookies and self-processing cookies.
Persistent cookie
ASIHTTPRequest allows you to use global storage to share cookies with all programs that use the CFNetwork or NSURLRequest interface.
If useCookiePersistence is set to YES, the cookie is stored in the shared NSHTTPCookieStorage container and is automatically reused by other requests. It is worth mentioning that ASIHTTPRequest will send cookies created by other programs to the server if these cookies are valid for specific requests ).
You can clear all the cookies created during the session:
- [ASIHTTPRequest setSessionCookies:nil];
Here, 'session cookies 'refer to all the cookies created in a session, rather than those with no expiration time, this cookie will be cleared at the end of the program ).
In addition, there is a convenient function clearSession to clear all cookies generated during the session and cache authorization data.
Process cookies by yourself
If you want to, you can close useCookiePersistence and manage a series of cookies for a request by yourself:
- // Create a cookie
- NSDictionary * properties = [[NSMutableDictionary alloc] init] autorelease];
- [Properties setValue: [@ "Test Value" encodedCookieValue] forKey: NSHTTPCookieValue];
- [Properties setValue: @ "ASIHTTPRequestTestCookie" forKey: NSHTTPCookieName];
- [Properties setValue: @ ".dreamingwish.com" forKey: NSHTTPCookieDomain];
- [Properties setValue: [NSDate dateWithTimeIntervalSinceNow: 60*60] forKey: NSHTTPCookieExpires];
- [Properties setValue: @ "/asi-http-request/tests" forKey: NSHTTPCookiePath];
- NSHTTPCookie * cookie = [[NSHTTPCookie alloc] initWithProperties: properties] autorelease];
-
- // This url returns the cookie value named 'asihttprequesttestcookie '.
- Url = [NSURL URLWithString: @ "http://www.dreamingwish.com/"];
- Request = [ASIHTTPRequest requestWithURL: url];
- [Request setUseCookiePersistence: NO];
- [Request setRequestCookies: [NSMutableArray arrayWithObject: cookie];
- [Request startSynchronous];
-
- // The output will be: I have 'test value' as the Value of 'asihttprequesttestcookie'
- NSLog (@ "% @", [request responseString]);