如何在 iOS7 中处理 NSURLAuthenticationChallenge



我想向有SSL问题的Web服务发布一些内容。我使用了以下方法:

NSURLConnection * urlConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];

它应该立即开始发送请求中已设置的数据;但是服务存在安全问题,无法正常工作。但是我想发送数据并想忽略安全问题;所以我使用了以下NSURLConnectionDelegate的方法:

- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace {
  return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
}
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
  [challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
  [challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
}

但它们已被弃用。我如何处理安全问题并告诉将数据传递到 Web 服务而不考虑它?

你应该像这样使用 willSendRequestForAuthenticationChallenge。

- (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
    self.challenge = challenge;
    [self askUserAcceptSSLError];
}
- (void)askUserAcceptSSLError
{
    // Ask user like UIAlertView or so.
    // Put these responses in UIAlertView delegate ...
    // If User accepts (or force this if you want ignore SSL certificate errors):
    [[self.challenge sender] 
        useCredential:[NSURLCredential credentialForTrust:self.challenge.protectionSpace.serverTrust]
        forAuthenticationChallenge:self.challenge];
    [[self.challenge sender] continueWithoutCredentialForAuthenticationChallenge:self.challenge];
    // If User deny request:
    [[self.challenge sender] cancelAuthenticationChallenge:self.challenge];
}

最新更新