NSURLConnection 实现webView显示HTTPS页面

我们在浏览器访问https页面的时候的,会弹出: 
信任证书

我们接下来信任证书以及显示出来

遵循协议

@interface ViewController ()<NSURLConnectionDataDelegate>
1
1
interface:

@interface ViewController ()<NSURLConnectionDataDelegate>
/**
  • 存储data数据

    */

    @property(nonatomic,strong)NSMutableData *dataM;
    /**

  • 访问url链接

    */

    @property(nonatomic,strong)NSURL *url;
    @property(nonatomic,weak)IBOutlet UIWebView *webView;
    @end

    实现代理方法:

    #pragma mark - NSURLSessionDataDelegate代理方法
    -(void)URLSession:(NSURLSession )session task:(NSURLSessionTask )task
    didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge

    completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * __nullable credential))completionHandler

    {

       NSLog(@"challenge = %@",challenge.protectionSpace.serverTrust);
       //判断是否是信任服务器证书
       if (challenge.protectionSpace.authenticationMethod ==NSURLAuthenticationMethodServerTrust)
       {
           //创建一个凭据对象
           NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
           //告诉服务器客户端信任证书
           [challenge.sender useCredential:credential forAuthenticationChallenge:challenge];
    
       }

    }
    /**

  • 接收到服务器返回的数据时调用

    */

    -(void)connection:(NSURLConnection )connection didReceiveData:(NSData )data
    {

       NSLog(@"接收到的数据%zd",data.length);
       [self.dataM appendData:data];

    }
    /**

  • 请求完毕

    */

    -(void)connectionDidFinishLoading:(NSURLConnection *)connection
    {

       NSString *html = [[NSString alloc]initWithData:self.dataM encoding:NSUTF8StringEncoding];
    
       NSLog(@"请求完毕");
       [self.webView loadHTMLString:html baseURL:self.url];

    }
    懒加载:
    -(NSMutableData *)dataM
    {

       if (_dataM == nil)
       {
           _dataM = [[NSMutableData alloc]init];
       }
       return _dataM;

    }


Eidesen
427 声望16 粉丝

专注iOS,Swift开发,总结了一下自己项目中遇到的问题,及解决方案。欢迎小伙伴讨论和多多指教--->记得顺手点个关注额(⊙o⊙)…。