将总是发送完成块?

最有可能是一个相当微不足道的问题,但完成块将始终使用[NSURLConnection sendAsynchronousRequest: ...]来调用? 或者我必须实现一个超时定时器?

请考虑以下情况,在调用之前添加MBProgressView ,并仅在完成块中将其删除:

 [self showHUDWithTitle:@"Configuring"]; [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) { if ([data length] >0 && error == nil) { [self hideHUDWithFlag:YES andTitle:@"Finished" andSubtitle:@"(Box was configured)"]; } else if ([data length] == 0 && error == nil) { [self hideHUDWithFlag:NO andTitle:@"Failed" andSubtitle:@"(Check box connection)"]; NSLog(@"Nothing was downloaded."); } else if (error != nil) { [self hideHUDWithFlag:NO andTitle:@"Error" andSubtitle:@"(Check box connection)"]; NSLog(@"Error = %@", error); } }]; 

是的,完成处理程序总是被调用。 如果请求由于超时而失败,则将设置error并且data = nil

NSURLRequest的默认超时时间为60秒,但在开始连接之前,您可以为request.timeoutInverval指定一个不同的值。 所以不需要额外的计时器。

补充:在超时的情况下:

  • [error domain]NSURLErrorDomain ,并且
  • [error code]NSURLErrorTimedOut

如果你只是想提出一个错误信息,你可以使用[error localizedDescription] ,这是“请求超时”。 在这种情况下。 (这可能取决于语言环境。)

 NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url cachePolicy:NSURLCacheStorageAllowed timeoutInterval:20]; 

[NSURLConnection sendAsynchronousRequest:…]在任何情况下肯定会调用完成块。 但是,如果要限制此过程的最长时间,也可以使用超时计时器。

对于进度条,你将如何增加价值? 而不是进度条,我build议你去与活动指标。

希望这可以帮助。