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

时间:2016-01-19 07:57:40

标签: objective-c iphone ios9 xcode7 nsurlsession

我在我的应用程序中使用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创建NSMutableURLRequest,动态URL由用户在设置页面中输入(例如https://100.100.25.25/sample)。

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

当我尝试使用带有最新服务器URL的NSURLSession访问服务器时 它始终返回错误&#34; NSURLConnection / CFURLConnection HTTP加载失败(kCFStreamErrorDomainSSL,-9843)&#34;。

注意:如果我的网址只包含字符(https://sample.com/sample),那么它的工作正常。如果它包含一些数字(https://100.100.25.25/sample)则不起作用。 鉴于URL不是实时的。它只是说 请帮我找到问题。提前致谢

1 个答案:

答案 0 :(得分:0)

这对我有用。资料来源: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);
    }
  }
}