I want to use AFNetworking with a batch operation. I want to download 3 json files.
How to add basic authentication with AFHTTPRequestOperation ?
NSMutab
Use AuthenticationChallengeBlock
to handle basic authentication challenge.
[operation setAuthenticationChallengeBlock:
^(NSURLConnection *connection, NSURLAuthenticationChallenge *challenge) {
NSURLCredential *cred = [NSURLCredential
credentialWithUser:@"username"
password:@"password"
persistence:NSURLCredentialPersistenceForSession];
[[challenge sender] useCredential:cred forAuthenticationChallenge:challenge];
}];
Edit:
Another option is to pass authentications in 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"];
Yet another solution :
NSURLCredential *credential = [NSURLCredential
credentialWithUser:@"login"
password:@"password"
persistence:NSURLCredentialPersistenceForSession];
[operation setCredential:credential];