Permalink
Browse files

Store cookies persistently

Since we don't have a hook into shutdown we have to write all the cookies each update, but that shouldn't be terrible.
  • Loading branch information...
1 parent d9d749b commit 83832783d8ccf623d669fd0173ea2d823f496fd2 @drapp drapp committed Feb 24, 2012
Showing with 16 additions and 8 deletions.
  1. +1 −1 StackMob/StackMob.m
  2. +1 −1 StackMob/StackMobCookieStore.h
  3. +14 −6 StackMob/StackMobCookieStore.m
View
@@ -70,7 +70,7 @@ + (StackMob *)setApplication:(NSString *)apiKey secret:(NSString *)apiSecret app
apiVersionNumber:apiVersion];
_sharedManager.requests = [NSMutableArray array];
_sharedManager.callbacks = [NSMutableArray array];
- _sharedManager.cookieStore = [[[StackMobCookieStore alloc] init] autorelease];
+ _sharedManager.cookieStore = [[[StackMobCookieStore alloc] initWithAppName:appName] autorelease];
}
return _sharedManager;
}
@@ -17,7 +17,7 @@
@interface StackMobCookieStore : NSObject
-- (StackMobCookieStore*)init;
+- (StackMobCookieStore*)initWithAppName:(NSString *)appName;
- (void) addCookies:(StackMobRequest *)request;
- (NSString *) cookieHeader;
@@ -15,18 +15,25 @@
#import "StackMobCookieStore.h"
@interface StackMobCookieStore()
-@property (nonatomic, retain) NSMutableDictionary *cookies;
- (void) addCookie:(NSHTTPCookie *)cookie;
@end
@implementation StackMobCookieStore
-@synthesize cookies = _cookies;
+static NSMutableDictionary *cookies;
+static NSString *cookieStoreKey;
-- (StackMobCookieStore*) init
+- (StackMobCookieStore*)initWithAppName:(NSString *)appName;
{
if ((self = [super init])) {
- _cookies = [[NSMutableDictionary alloc] init];
+
+ cookieStoreKey = [@"stackmob." stringByAppendingString:appName];
+ NSData *storedCookes = [[NSUserDefaults standardUserDefaults] objectForKey:cookieStoreKey];
+ if ([storedCookes length]) {
+ cookies = [NSKeyedUnarchiver unarchiveObjectWithData:storedCookes];
+ } else {
+ cookies = [[NSMutableDictionary alloc] init];
+ }
}
return self;
}
@@ -43,14 +50,15 @@ - (void) addCookies:(StackMobRequest *)request
- (void) addCookie:(NSHTTPCookie *)cookie
{
- [_cookies setObject:cookie forKey:[cookie name]];
+ [cookies setObject:cookie forKey:[cookie name]];
+ [[NSUserDefaults standardUserDefaults] setObject:[NSKeyedArchiver archivedDataWithRootObject:cookies] forKey:cookieStoreKey];
}
- (NSString *) cookieHeader
{
BOOL first = YES;
NSString * cookieString = @"";
- for(NSHTTPCookie *cookie in [_cookies allValues]) {
+ for(NSHTTPCookie *cookie in [cookies allValues]) {
if ([[cookie expiresDate] compare:[NSDate date]] != NSOrderedAscending)
{
cookieString = [cookieString stringByAppendingFormat:@"%@%@=%@", (first ? @"" : @";"), [cookie name], [cookie value]];

0 comments on commit 8383278

Please sign in to comment.