Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AFNetworking 2 authentication with AFHTTPRequestOperation

I want to use AFNetworking with a batch operation. I want to download 3 json files.

How to add basic authentication with AFHTTPRequestOperation ?

NSMutableArray *mutableOperations = [NSMutableArray array];

for (NSString *fileURL in filesToDownload) {
    NSURLRequest *request = [NSURLRequest 
                                requestWithURL:[NSURL URLWithString:fileURL]];
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]
                                                initWithRequest:request];
    [operation  setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation
                                                , id responseObject) {
        NSLog(@"success: %@", operation.responseString);
    }
    failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"error: %@",  operation.responseString);
    }];
    [mutableOperations addObject:operation];
}

NSArray *operations = [AFURLConnectionOperation batchOfRequestOperations:mutableOperations 
                                    progressBlock:^(NSUInteger numberOfFinishedOperations
                                        , NSUInteger totalNumberOfOperations) {
    NSLog(@"%d of %d complete", numberOfFinishedOperations, totalNumberOfOperations);
} completionBlock:^(NSArray *operations) {
    NSLog(@"All operations in batch complete");
}];

[[NSOperationQueue mainQueue] addOperations:operations waitUntilFinished:NO];

Thank you very much

like image 408
mdespeuilles Avatar asked Oct 25 '13 10:10

mdespeuilles


1 Answers

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];
like image 96
OnkarK Avatar answered Oct 08 '22 18:10

OnkarK