NSURLConnection同步,异步与SSL

来源:互联网 发布:java线程笔试题 编辑:程序博客网 时间:2024/05/17 02:58
但是异步模式下带来了一个新的问题,很多情况下,网络请求不在主线程,或者界面等待网络结果,不在主线程的时候,调用线程如果生命周期over,下面这些可能都没有调用到,导致得不到想要得效果,所以需要在NSURLConnection请求后面加点东西来阻塞

while(!finished) {

[[NSRunLoop currentRunLooprunMode:NSDefaultRunLoopMode beforeDate:[NSDatedistantFuture]];

}


好了,现在我们看看SSL的问题,在NSURLConnnection本来有方法可以跳过ssl检查,可惜被apple无情的私有了,所以同步的数据请求肯定不行了,看看文档,只能通过异步delegate的方式了

- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace 

{

return [protectionSpace.authenticationMethodisEqualToString:NSURLAuthenticationMethodServerTrust];

}

- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge 

{

if ([challenge.protectionSpace.authenticationMethodisEqualToString:NSURLAuthenticationMethodServerTrust])

if ([trustedHosts containsObject:challenge.protectionSpace.host])

[challenge.sender useCredential:[NSURLCredentialcredentialForTrust:challenge.protectionSpace.serverTrust]forAuthenticationChallenge:challenge];

[challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];

}


第一个方法会根据你的URL来判断是否需要做认证

第二个方法是认证的过程,if ([trustedHosts containsObject:challenge.protectionSpace.host]),这行代码注释掉,就可以自动所有SSL通过,否则,你可以加一些Trust的hosts,其他的不通过就行了!!!

0 0