Question

I have a subclass of AFHTTPClient with NSCoding protocol methods implemented:

- (id)initWithCoder:(NSCoder *)aDecoder {

  self = [super initWithCoder:aDecoder];

  if (!self)
    return nil;

  self.isLoggedIn = [aDecoder decodeBoolForKey:@"isLoggedIn"];

  return self;
}

- (void)encodeWithCoder:(NSCoder *)aCoder {
  [super encodeWithCoder:aCoder];
  [aCoder encodeBool:self.isLoggedIn forKey:@"isLoggedIn"];
}

I also implemented the method for setting default header for the token & there I archive the client:

- (void)setAuthorizationHeaderWithToken:(NSString *)token {
  [self setDefaultHeader:@"Authorization" value:[NSString stringWithFormat:@"OAuth %@", token]];

  [self setIsLoggedIn:YES];

  NSData *data = [NSKeyedArchiver archivedDataWithRootObject:self];
  [[NSUserDefaults standardUserDefaults] setObject:data forKey:kGCClient];
  [[NSUserDefaults standardUserDefaults] synchronize];
}

And I deserialize the client in the - (id)initWithBaseURL:(NSURL *)url implementation in my subclass:

- (id)initWithBaseURL:(NSURL *)url {

  NSData *data = [[NSUserDefaults standardUserDefaults] objectForKey:kGCClient];
  GCClient *client = [NSKeyedUnarchiver unarchiveObjectWithData:data];

  if (client)
    return self = client;

  self = [super initWithBaseURL:url];

  if (!self) {
    return nil;
  }

  [self setIsLoggedIn:NO];

  return self;
}

The issue is that once I'm logged in, the next time I open the app it crushes on the deserialization of the client, in the AFHTTPClient class - (id)initWithCoder:(NSCoder *)aDecoder method, on the first try to decode a object & in debugger it says that the value returned is not an Objective-C object.

NSURL *baseURL = [aDecoder decodeObjectForKey:@"baseURL"];
Was it helpful?

Solution

Two things:

  • Use the Keychain, rather than NSUserDefaults, to store credentials.
  • Instead of messing with NSCoding, simply override -initWithBaseURL, (making sure to call super, of course), and set the Authorization header based on the value stored in the keychain (if it exists). The isLoggedIn property could (and should) be defined as a derived readonly property, which returns YES when the Authorization header is present, and NO otherwise.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top