我一直試圖使用NSURLSession
來信任一個證書,因爲從macOS 10.11開始已棄用NSURLConnection
變體。我試圖在基於WebKit的應用程序中實現NSURLSession
,並且在證書被信任後,什麼都不會發生,並且如果我重新加載網頁,則控制檯中會出現相同的錯誤,表示證書不受信任。使用NSURLSession信任無效證書
我的代碼如下:
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:[defaults objectForKey:@"lastSession"]]];
NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration:defaultConfigObject delegate:self delegateQueue:[NSOperationQueue mainQueue]];
NSURLSessionDataTask *dataTask = [defaultSession dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(@"Success");
}];
[dataTask resume];
下面是我對didReceiveChallenge
方法:
- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential *))completionHandler {
NSLog(@"Received auth challenge");
if([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
NSURL *baseURL = [NSURL URLWithString:[defaults objectForKey:@"lastSession"]];
if([challenge.protectionSpace.host isEqualToString:baseURL.host]) {
NSLog(@"Trusting connection to host %@", challenge.protectionSpace.host);
NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
[challenge.sender useCredential:credential forAuthenticationChallenge:challenge];
completionHandler(NSURLSessionAuthChallengeUseCredential, credential);
NSLog(@"Trusted webpage successfully");
}
}
}
有我丟失的東西嗎?一些幫助肯定會被讚賞...