[英]Is NSURLConnection sendAsynchronousRequest completion block executed on the main thread?
[英]Will [NSURLConnection sendAsynchronousRequest: …] always send completion block?
很可能是一个相当简单的问题,但是总是会使用[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:...]肯定会在任何场景中调用完成块。 但是,如果要将此过程限制为最大时间,也可以使用超时计时器。
对于进度条,您将如何递增值? 我会建议你选择活动指标,而不是进度条。
希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.