使用UIWebview和NSURLSession加载自签名的https url

时间:2016-02-15 20:31:09

标签: ios objective-c uiwebview nsurlsession

我正在尝试加载自签名网站。我知道我可以使用NSURLConnection通过使用此代码来提供凭据

UIWebView to view self signed websites (No private api, not NSURLConnection) - is it possible?

- (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
    [challenge.sender useCredential: [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge: challenge];
}

并在

中加载请求
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [self.webviewVc.webview loadRequest:_FailedRequest];
}    

但是当我尝试使用NSURLSession做类似的事情时,我总是得到错误

NSURLConnection/CFURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9813)

我的代码看起来像这样

- (BOOL)loadWithRequest:(NSURLRequest *)request
{
  if (!_Authenticated ) {
      _FailedRequest = request;
      NSURLSessionConfiguration* defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
      NSURLSession *session = [NSURLSession sessionWithConfiguration:defaultConfigObject delegate:self delegateQueue:nil];
      NSURLSessionDataTask * task = [session dataTaskWithRequest:_FailedRequest];
      [task resume];
      return NO;
  }
  _Authenticated = NO;
  return YES;
}

-(void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler
{
  completionHandler(NSURLSessionAuthChallengeUseCredential, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]);
}

-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
{
  [self.webviewVc.webview loadRequest:_FailedRequest];
}

有什么想法吗? 感谢

0 个答案:

没有答案