微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

ios – AFNetworking 2认证与AFHTTPRequestOperation

我想使用AFNetworking进行批处理操作.我想下载3个json文件.

如何使用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];

非常感谢你

解决方法

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

原文地址:https://www.jb51.cc/iOS/330047.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐