我有以下连接到SSL网页的简单代码

NSMutableURLRequest *urlRequest=[NSMutableURLRequest requestWithURL:url];
[ NSURLConnection sendSynchronousRequest: urlRequest returningResponse: nil error: &error ];

除非它给出一个错误,如果证书是自签名的Error Domain=NSURLErrorDomain Code=-1202 UserInfo=0xd29930 "untrusted server certificate".,是否有办法将其设置为接受连接(就像在浏览器中一样,您可以按Accept(接受))或绕过它?

推荐答案

有一个受支持的API可以实现这一点!将类似以下内容添加到您的NSURLConnection代理:

- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace {
  return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
}

- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
  if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust])
    if ([trustedHosts containsObject:challenge.protectionSpace.host])
      [challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];

  [challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
}

注意,如果需要,在向用户呈现对话框之后,connection:didReceiveAuthenticationChallenge:可以将其消息发送到Challenge.sender(更晚),等等.

Ios相关问答推荐

[NSJSONSerializationdataWithJSONObserver:选项:错误:]:SON写入中无效的顶级类型

实例方法wait在异步上下文中不可用;请改用TaskGroup;这是Swift 6中的错误''

与iPadOS中带有扣件的模式相似的组件是什么?

如何在将EXPO更新到50.0后修复react 本机错误

swiftui 图像放大时无法正确拖动

确保方法调配的安全有效实施

在iOS中使用Swift,即时更改应用语言后,立即改变外观会出现问题

将 URLCache 子类与 URLSession 一起使用

具有一个参数/参数的泛型类的泛型类

SwiftUI Disclosure Group 文本对齐

SensorKit - 获取数据不调用结果委托函数

向左或向右移动时如何水平翻转sprite?

使用 RxDatasources 作为数据源时如何填充自定义页眉/页脚视图

iOS 中的 [Class new] 和 [[Class alloc] init] 有什么区别?

iOS 11 navigationItem.titleView 宽度未设置

Xcode 项目格式:3.1、3.2、6.3 和 8.0 有什么区别?

针对 Xcode 中的 iPad 选项

如何在键盘上方添加工具栏?

自动布局:是什么创建了名为 UIView-Encapsulated-Layout-Width & Height 的约束?

使用 swift 3 在 UIView 上添加阴影