使用object 为您使用此方法NSURLRequest
下载的 evrey 请求指定超时。requestWithURL:cachePolicy:timeoutInterval:
请检查您NSURLConnection
的委托是否已设置并响应该connection:didFailWithError:
方法。ANSURLConnection
调用此方法或connectionDidFinishLoading:
在连接完成时调用。
处理'didFailWithError'方法并使用NSError
对象检查失败的原因。
但是,如果您从服务器获得响应并且响应时间很慢,则使用NSTimer
. 创建用于下载数据的 Helper 类,以便您可以通过创建多个实例并在其中设置 NSTimer 来重用该类进行多次下载,如果下载在 30 秒内完成,则使计时器无效,否则取消下载[self.connection cancel]
。
请检查以下代码:
- (void)_startReceive
// Starts a connection to download the current URL.
{
BOOL success;
NSURL * url;
NSURLRequest * request;
// Open a connection for the URL.
request = [NSURLRequest requestWithURL:url];
assert(request != nil);
self.connection = [NSURLConnection connectionWithRequest:request delegate:self];
assert(self.connection != nil);
// If we've been told to use an early timeout for get complete response within 30 sec,
// set that up now.
self.earlyTimeoutTimer = [NSTimer scheduledTimerWithTimeInterval:30.0 target:self selector:@selector(_earlyTimeout:) userInfo:nil repeats:NO];
}
}
- (void)_stopReceiveWithStatus:(NSString *)statusString
// Shuts down the connection and displays the result (statusString == nil)
// or the error status (otherwise).
{
if (self.earlyTimeoutTimer != nil) {
[self.earlyTimeoutTimer invalidate];
self.earlyTimeoutTimer = nil;
}
if (self.connection != nil) {
[self.connection cancel];
self.connection = nil;
}
}
- (void)_earlyTimeout:(NSTimer *)timer
// Called by a timer (if the download is not finish)
{
[self _stopReceiveWithStatus:@"Early Timeout"];
}
- (void)connection:(NSURLConnection *)conn didReceiveResponse:(NSURLResponse *)response
// A delegate method called by the NSURLConnection when the request/response
// exchange is complete.
{ }
- (void)connection:(NSURLConnection *)conn didReceiveData:(NSData *)data
// A delegate method called by the NSURLConnection as data arrives. We just
// write the data to the file.
{ }
- (void)connection:(NSURLConnection *)conn didFailWithError:(NSError *)error
// A delegate method called by the NSURLConnection if the connection fails.
{
NSLog(@"didFailWithError %@", error);
// stop Receive With Status Connection failed
}
- (void)connectionDidFinishLoading:(NSURLConnection *)conn
// A delegate method called by the NSURLConnection when the connection has been
// done successfully. We shut down the connection with a nil status.
{
NSLog(@"connectionDidFinishLoading");
// If control reach here before timer invalidate then save the data and invalidate the timer
if (self.earlyTimeoutTimer != nil) {
[self.earlyTimeoutTimer invalidate];
self.earlyTimeoutTimer = nil;
}
}