Ios AFHTTPRequestOperation的AF2网络身份验证
我想使用带有批处理操作的AFNetworking。我想下载3个json文件 如何使用AFHTTPRequestOperation添加基本身份验证Ios AFHTTPRequestOperation的AF2网络身份验证,ios,afnetworking-2,Ios,Afnetworking 2,我想使用带有批处理操作的AFNetworking。我想下载3个json文件 如何使用AFHTTPRequestOperation添加基本身份验证 NSMutableArray *mutableOperations = [NSMutableArray array]; for (NSString *fileURL in filesToDownload) { NSURLRequest *request = [NSURLRequest
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
处理基本身份验证挑战
[operation setAuthenticationChallengeBlock:
^(NSURLConnection *connection, NSURLAuthenticationChallenge *challenge) {
NSURLCredential *cred = [NSURLCredential
credentialWithUser:@"username"
password:@"password"
persistence:NSURLCredentialPersistenceForSession];
[[challenge sender] useCredential:cred forAuthenticationChallenge:challenge];
}];
编辑:
另一个选项是在请求头中传递身份验证
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"];
另一个解决方案:
NSURLCredential *credential = [NSURLCredential
credentialWithUser:@"login"
password:@"password"
persistence:NSURLCredentialPersistenceForSession];
[operation setCredential:credential];
谢谢你,但是
AuthenticationChallengeBlock
不再存在于一个新的2银行中,因为它可以工作。我找到了另一个解决方案:NSURLCredential*credential=[nsurlCredentialCredentialWithUser:_loginField.text密码:_passwordField.text持久性:NSURLCredentialPersistenceForSession];[操作设置凭证:凭证]
@mdespeuilles编辑答案并添加您的解决方案。这将帮助其他人。谢谢你的帮助:-)