Skip to content

Instantly share code, notes, and snippets.

@fahied
Created September 23, 2014 08:59
Show Gist options
  • Save fahied/e4ac68b142dfab8f04e5 to your computer and use it in GitHub Desktop.
Save fahied/e4ac68b142dfab8f04e5 to your computer and use it in GitHub Desktop.
add Authentication to AFHTTPRequestOperation
//1. using completion block
[operation setAuthenticationChallengeBlock:
^(NSURLConnection *connection, NSURLAuthenticationChallenge *challenge) {
NSURLCredential *cred = [NSURLCredential
credentialWithUser:@"username"
password:@"password"
persistence:NSURLCredentialPersistenceForSession];
[[challenge sender] useCredential:cred forAuthenticationChallenge:challenge];
}];
//2. add to request header
NSURLMutableRequest *request = [NSURLMutableRequest
requestWithURL:[NSURL URLWithString:fileURL]];
NSData* authData = [[[NSString
stringWithFormat:@"username:password"]
stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]
dataUsingEncoding: NSASCIIStringEncoding];
NSString *finalAuth = [authData base64EncodedString];
finalAuth = [NSString stringWithFormat:@"Basic %@",finalAuth];
[request setValue:finalAuth forHTTPHeaderField:@"Authorization"];
//3. add credentials to ops
NSURLCredential *credential = [NSURLCredential
credentialWithUser:@"login"
password:@"password"
persistence:NSURLCredentialPersistenceForSession];
[operation setCredential:credential];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment