Created
September 23, 2014 08:59
-
-
Save fahied/e4ac68b142dfab8f04e5 to your computer and use it in GitHub Desktop.
add Authentication to AFHTTPRequestOperation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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