我同时运行很多异步(委托,不阻止)NSURLConnections
,当我遇到局域网服务器时,它们都会很快回来。
每隔一段时间,一个NSURLConnection
就会消失,永不返回。
connection:willSendRequest:
被调用,但connection:didReceiveResponse:
(并且失败)不是。
有什么想法吗?我想知道我是否应该使用CFNetwork
进行简单的替换。
编辑:显示的代码真的不多。我所做的是创建了一个下载文件的包装类。我会注意到,当我在一个单独的队列上运行连接时,问题发生 less - 但仍然会发生。
我正在做的一般要点是为每个单元格创建一个下载请求,因为tableview滚动(在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];
}
}
答案 0 :(得分:1)
在探查器中探索之后,我发现了一个领先优势,它给了我一个预感。
我的凭据失败了(不知道为什么......)所以previousFailureCount不是0,因此我没有使用我的凭证对象。
将代码更改为此,我没有问题:
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
if(_credential) {
[[challenge sender] useCredential:_credential forAuthenticationChallenge:challenge];
}
}
答案 1 :(得分:0)
NSURLConnection
会发送didReceiveResponse
或didFailWithError
。
通常,您在didFailWithError
发生之前处理超时。