NSURLConnection/CFURLConnection HTTP 加载失败错误(kCFStreamErrorDomainSSL,-9843)

NSURLConnection/CFURLConnection HTTP load failed error (kCFStreamErrorDomainSSL, -9843)

我在我的应用程序中使用 NSURLSession 将数据发送到服务器。服务器URL可能是任意的,可能会动态变化

所以我在我的 plist 文件中添加了以下内容

<key>NSAppTransportSecurity</key>
    <dict>
        <key>NSAllowsArbitraryLoads</key>
        <true/>
    </dict>

因为用户可以从我的应用程序中的设置页面手动更改服务器 URL。因此,当我尝试发送数据时,NSURLRequest 将配置最新的服务器 URL.

我的密码是

[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
NSURLSession *session = [NSURLSession sharedSession];
[[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

//some of my codes

 }] resume];

我将从动态 URL 创建 NSMutableURL 请求,该请求由用户在设置页面中输入(例如 https://100.100.25.25/sample)。

NSMutableURLRequest *dataRequest = [NSMutableURLRequest requestWithURL:serverAddress 
                                                               cachePolicy:NSURLRequestUseProtocolCachePolicy 
                                                           timeoutInterval:60.0];   

当我尝试使用 NSURLSession 与最新服务器 URL 访问服务器时 它总是 return 错误 "NSURLConnection/CFURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9843)".

注意:如果我的 URL 只包含字符 (https://sample.com/sample) 那么它工作正常。如果它包含一些数字(https://100.100.25.25/sample)那么它不起作用。 鉴于 URL 未直播。只是说 请帮我找出问题所在。提前致谢

这对我有用。资料来源:How do I accept a self-signed SSL certificate using iOS 7's NSURLSession and its family of delegate methods for development purposes?

NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfiguration delegate:self delegateQueue:Nil];
...
...
- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential *))completionHandler{
  if([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]){
    if([challenge.protectionSpace.host isEqualToString:@"mydomain.com"]){
      NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
      completionHandler(NSURLSessionAuthChallengeUseCredential,credential);
    }
  }
}