【发布时间】:2020-07-10 04:18:12
【问题描述】:
我是 Objective-C 的新手,我一直在研究一些旧代码,试图动态检查是否应该忽略 SSL 证书错误。我已经设置了一个NSURLConnection 委托及其方法:
@interface Downloader : NSObject <NSURLConnectionDelegate>
-(void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:( NSURLAuthenticationChallenge *)challenge;
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error;
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;
-(void)connectionDidFinishLoading:(NSURLConnection *)connection;
实施:
-(void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge{
if([self.ignoreCertificateErrors isEqualToString:@"false"]){
if([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust])
[challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
}
[challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
CFRunLoopStop(CFRunLoopGetCurrent());
_downloadError = error;
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[_downloadData appendData: data];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSError * error;
[_downloadData writeToFile:_downloadDest options:NSDataWritingAtomic error:&error];
}
我面临的问题是-(void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:( NSURLAuthenticationChallenge *)challenge 在每次下载之前都不会被调用,因此不会检查该属性,并且无论变量的值如何,都会进行下载。
有谁知道什么会导致NSURLConnection 忽略它自己的委托方法?
(另外,使用NSRunLoop currentRunLoop异步下载
我知道这是一个老问题,但其他答案都没有为我解决这个问题。
这是执行异步下载的代码摘录:
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
dispatch_queue_t downloadQueue = dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0 );
dispatch_async(downloadQueue, ^{
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request
delegate:self
startImmediately:NO];
[connection scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[connection start];
[ [ NSRunLoop currentRunLoop ] run ];
dispatch_semaphore_signal(semaphore);
[connection release];
});
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
【问题讨论】:
-
控制台告诉你什么?
NSURLConnection不需要应用程序传输吗?我已经超过 4 年没有使用它了。所以我不记得它是如何工作的。 -
只有这一个没有被调用的委托方法吗?如果没有人被调用,则表明存在许多问题中的任何一个。如果只有这个被调用,那表明一些不同的东西。
-
ignoreCertificateErrors是什么数据类型? -
请分享您如何设置
delegate。作为委托的类也应该符合委托协议:@interface MyClass:NSObject<NSURLConnectionDelegate> {...} -
@Rob 刚刚检查,其他方法也没有被调用
标签: objective-c macos ssl ssl-certificate nsurlconnection