我在这里有这个代码将我登录到一个URL,我的问题是当我尝试删除它不起作用的信用时,但我在网上找到了一个解决方案:
If you're using NSURLSession, invalidate the session and create a new one, e.g.:
[self.session invalidateAndCancel];
self.session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:nil];
This will clear session-scoped credentials.
所以我的问题是,我可以将NSURLSession与AFNetworking一起使用:
NSURL *url = [NSURL URLWithString:kIP];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]
initWithRequest:request];
NSURLCredential *credential = [NSURLCredential
credentialWithUser:user
password:password
persistence:NSURLCredentialPersistenceForSession];
[operation setCredential:credential];
[[NSOperationQueue mainQueue] addOperation:operation];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
if (completionHandler) {
completionHandler(responseObject, nil);
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
if (completionHandler) {
completionHandler(nil, error);
}
}];
[operation start];
更新
我开始这样做了:
NSURL *url = [NSURL URLWithString:kIP];
NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:sessionConfiguration];
[manager setResponseSerializer:[AFJSONResponseSerializer serializer]];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[[manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
if (completionHandler) {
completionHandler(responseObject, nil);
}
}] resume];
如何为此添加用户名和密码?
答案 0 :(得分:0)
尝试使用AFNSURLSession而不是AFHTTPRequestOperation。在AFNSURLSession中,您可以为委托setSessionDidReceiveAuthenticationChallengeBlock提供一个块,您可以在其中提供必要的凭据。
来自AFNSURLSession.h:
/**
Sets a block to be executed when a connection level authentication challenge has occurred, as handled by the `NSURLSessionDelegate` method `URLSession:didReceiveChallenge:completionHandler:`.
@param block A block object to be executed when a connection level authentication challenge has occurred. The block returns the disposition of the authentication challenge, and takes three arguments: the session, the authentication challenge, and a pointer to the credential that should be used to resolve the challenge.
*/
- (void)setSessionDidReceiveAuthenticationChallengeBlock:(NSURLSessionAuthChallengeDisposition (^)(NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential))block;