AFNetworking 2.0: How to persist an NSURLCredential across app launches

644 views Asked by At

I am creating an NSURLCredential with NSURLCredentialPersistencePermanent and using it to authenticate an AFHTTPRequestOperation as follows:

AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
NSURLCredential *credential = [NSURLCredential credentialWithUser:username password:password persistence:NSURLCredentialPersistencePermanent];
[operation setCredential:credential];

Once authenticated, the credential no longer needs to be set on future operations.

However, once I re-launch the app, while the credential is still present in [NSURLCredentialStorage sharedCredentialStorage], the next AFHTTPRequestOperation is no longer authenticated and returns an access denied response.

Why doesn't AFNetworking recognize the credential which exists in the shared credential storage?

1

There are 1 answers

0
titaniumdecoy On

The shouldUseCredentialStorage property of AFURLConnectionOperation (the superclass of AFHTTPRequestOperation) is documented to be "`YES` by default.". This value is overwritten by AFHTTPRequestOperationManager with its own shouldUseCredentialStorage value when a new operation is created.

Due to a bug in AFHTTPRequestOperationManager, shouldUseCredentialStorage is never initialized to YES (even though its default value is documented as such).

The solution (for now) is to manually set the request or operation manager's shouldUseCredentialStorage property to YES.

Link to bug report on GitHub