我正在开发一个从 URL 获取图像的 iPhone 应用程序。我正在使用 'NSData dataWithContentsOfUrl] 并且效果很好。但是,正如您可能已经猜到的那样,请求是同步的。
我希望请求是异步的。所以,我尝试使用 NSURLConnection 的 sendAsynchronousRequest() 调用。但这会在方法 'didFailWithError' 中返回以下错误:
错误域=kCFErrorDomainCFNetwork 代码=310“与安全 Web 代理服务器 (HTTPS) 通信时出现问题。
有人可以帮忙吗?
这是我的 NSURLConnection 代码片段:
NSURL *url = [NSURL URLWithString:notePicUrl];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:100.0];
//NSOperationQueue *queue = [[NSOperationQueue alloc] init];
NSURLConnection* _connection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self startImmediately:NO];
self.port = [NSPort port];
self.runLoop = [NSRunLoop currentRunLoop];
[self.runLoop addPort:self.port forMode:NSDefaultRunLoopMode];
[_connection scheduleInRunLoop:self.runLoop forMode:NSDefaultRunLoopMode];
[_connection start];
while (self.finished != YES ) {
[self.runLoop runUntilDate:[NSDate dateWithTimeIntervalSinceNow: 0.1]];
}
[self.runLoop removePort:[self port] forMode:NSDefaultRunLoopMode];
[_connection unscheduleFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
和 NSURLConnectionDelegate 方法(尚未实现;只是测试首先看看它是否有效)......
-(void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse*)response
{
NSLog(@"didReceiveResponse");
//_data = [[NSMutableData alloc] init]; // _data being an ivar
}
-(void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data
{
NSLog(@"didReceiveData");
//[_data appendData:data];
}
-(void)connection:(NSURLConnection*)connection didFailWithError:(NSError*)error
{
NSLog(@"didFailWithError %@", [error description]);
// Handle the error properly
}
-(void)connectionDidFinishLoading:(NSURLConnection*)connection
{
NSLog(@"connectionDidFinishLoading");
//[self handleDownloadedData]; // Deal with the data
}