将[NSURLConnection sendAsynchronousRequest:...]总是发送完成块? [英] Will [NSURLConnection sendAsynchronousRequest: ...] always send completion block?

查看:156
本文介绍了将[NSURLConnection sendAsynchronousRequest:...]总是发送完成块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很可能是一个相当琐碎的问题,但将完成块总是使用 [NSURLConnection sendAsynchronousRequest:...] 调用?或者我必须实现一个超时定时器吗?

Most likely a rather trivial question but will the completion block always be called using [NSURLConnection sendAsynchronousRequest: ...]? OR do I have to implement a timeout timer?

考虑下面的情况,我在呼叫之前添加 MBProgressView 仅在完成块中删除它:

Consider the following where I add a MBProgressView before the call and remove it ONLY in the completion block:

[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);
     }
 }];


推荐答案

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

Yes, the completion handler is always called. If the request fails due to a timeout, the error will be set and data = nil.

A NSURLRequest 的默认超时为60秒,但您可以为 request.timeoutInverval指定不同的值,然后开始连接。

A NSURLRequest has a default timeout of 60 seconds, but you can assign a different value to request.timeoutInverval before starting the connection. So there is no need for an extra timer.

添加:在超时的情况下:


  • [error domain] NSURLErrorDomain

  • [错误代码] NSURLErrorTimedOut

  • [error domain] is NSURLErrorDomain, and
  • [error code] is NSURLErrorTimedOut,

如果你只是想出现错误信息,可以使用 [error localizedDescription] 时间到。在这种情况下。 (这可能取决于区域设置。)

If you just want to present an error message, you can use [error localizedDescription], which is "The request timed out." in this case. (This may depend on the locale.)

这篇关于将[NSURLConnection sendAsynchronousRequest:...]总是发送完成块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆