使用AFHTTPRequestOperation AFNetworking 2authentication

我想通过批处理操作来使用AFNetworking。 我想下载3个json文件。

如何使用AFHTTPRequestOperation添加基本身份validation?

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]; 

非常感谢你

使用AuthenticationChallengeBlock来处理基本的身份validation挑战。

 [operation setAuthenticationChallengeBlock: ^(NSURLConnection *connection, NSURLAuthenticationChallenge *challenge) { NSURLCredential *cred = [NSURLCredential credentialWithUser:@"username" password:@"password" persistence:NSURLCredentialPersistenceForSession]; [[challenge sender] useCredential:cred forAuthenticationChallenge:challenge]; }]; 

编辑:

另一种select是在请求标头中传递authentication。

 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"]; 

又一个解决scheme:

 NSURLCredential *credential = [NSURLCredential credentialWithUser:@"login" password:@"password" persistence:NSURLCredentialPersistenceForSession]; [operation setCredential:credential];