我同时运行了很多异步(委托,而不是阻塞)NSURLConnections
,当我访问局域网服务器时,它们都会很快返回。
每隔一段时间,一个人NSURLConnection
就会消失,永远不会回来。
connection:willSendRequest:
被调用但connection:didReceiveResponse:
(和失败)不是。
有任何想法吗?我想知道是否应该使用CFNetwork
代替进行简单的直接替换。
编辑:实际上没有太多代码可以显示。我所做的是创建一个包装类来下载文件。我会注意到,当我在单独的队列上运行连接时,问题发生的较少- 但仍然会发生。
我正在做的一般要点是在表格视图滚动时为每个单元格创建一个下载请求(在 中cellForRowAtIndexPath
),然后如果单元格仍然可见,则将图像文件异步加载到表格单元格。
_request = [NSMutableURLRequest requestWithURL:_URL];
_request.cachePolicy = NSURLRequestReloadIgnoringCacheData;
_request.timeoutInterval = _timeoutInterval;
if(_lastModifiedDate) {
[_request setValue:[_lastModifiedDate RFC1123String] forHTTPHeaderField:@"If-Modified-Since"];
}
_connection = [[NSURLConnection alloc] initWithRequest:_request
delegate:self
startImmediately:NO];
[_connection start];
根据要求,实例变量:
NSMutableURLRequest *_request;
NSURLConnection *_connection;
和委托方法:
- (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response {
NSLog(@"%@ send", _URL);
return request;
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSLog(@"%@ response", _URL);
_response = (id)response;
// create output stream
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
_receivedLength += data.length;
_estimatedProgress = (Float32)_receivedLength / (Float32)_response.expectedContentLength;
[_outputStream write:data.bytes maxLength:data.length];
// notify delegate
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
// close output stream
// notify delegate
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(@"%@ failure", _URL);
// notify delegate
}
- (void)connection:(NSURLConnection *)connection
didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
if(_credential && challenge.previousFailureCount == 0) {
[[challenge sender] useCredential:_credential forAuthenticationChallenge:challenge];
}
}