Невозможно обойти эту схему проверки SSL, и через некоторое время попробовать и искать повсюду для решения, мне пришлось реализовать класс, чтобы сделать именно это.
Поскольку преимущество NSString в stringWithContentsOfURL должно быть синхронным, я должен был убедиться, что мой был также. Это, вероятно, немного большая для всех целей, но вы получаете суть этого.
@interface NZStringLoader : NSObject
@property (assign, readonly, nonatomic) BOOL done;
@property (strong, readonly, nonatomic) NSString *result;
@property (strong, readonly, nonatomic) NSURLConnection *conn;
- (id) initWithURL:(NSURL*)u;
- (void) loadSynchronously;
@end
@implementation NZStringLoader
@synthesize done = _done, result = _result, conn = _connection;
- (id) initWithURL:(NSURL*)u {
NSURLRequest *req = [[NSURLRequest alloc] initWithURL:u
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:10.0];
_connection = [NSURLConnection connectionWithRequest:req delegate:self];
_done = NO;
return self;
}
- (void) loadSynchronously {
[_connection start];
while(!_done)
[[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:.15]];
}
#pragma mark -
#pragma mark NSURLConnectionDelegate
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
_done = YES;
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
RTLog(@"%@", [error localizedDescription]);
_done = YES;
}
- (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])
[challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
[challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
if(_result == nil)
_result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
else
_result = [_result stringByAppendingString:[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]];
}
@end
И он используется так:
NZStringLoader *sl = [[NSStringLoader alloc] initWithURL:u];
[sl loadSynchronously];
result = sl.result;
Я предполагаю, что я мог сделать это только один вызов, если бы я хотел.
У меня проблема. Как вы его решили? –