【问题标题】:NSURLConnection async thread connection closureNSURLConnection 异步线程连接关闭
【发布时间】:2014-06-27 12:01:27
【问题描述】:

我使用 NSURLConnection 在与主线程分离的线程中从 Internet 获取一些数据: 我把它放在我的 JSONViewController.h 中:

#import <UIKit/UIKit.h>

@interface JSONViewController : UIViewController <NSURLConnectionDelegate> {
   BOOL firstTime;
   NSMutableData *_responseData;
}
@end

我使用此代码在 JSONViewController.m 中启动连接:

NSURLRequest *request;
 if (self.jsonItem == nil) {
        request = [NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",MY_URL,@"testvalue"]]];
  }else {
        request = [NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",MY_URL,(NSString *)self.jsonItem]]];
  }
  NSLog(@"json Item = %@",self.jsonItem);


  // Create url connection and fire request
  NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];

我也实现了那些与 NSURLConnection 协议相关的功能:

#pragma mark NSURLConnection Delegate Methods
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    _responseData = [[NSMutableData alloc] init];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [_responseData appendData:data];
}

- (NSCachedURLResponse *)connection:(NSURLConnection *)connection
                  willCacheResponse:(NSCachedURLResponse*)cachedResponse {
    return nil;
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {}

一切正常。 问题是:我得到结果并且连接应该完成后,为什么在导航栏上方的运营商字段附近仍然看到这个小指示器?我应该手动停止连接吗?

【问题讨论】:

    标签: ios iphone objective-c nsurlconnection


    【解决方案1】:

    在您的代码中的某处,您应该会找到类似这样的内容:

    UIApplication* app = [UIApplication sharedApplication];
    app.networkActivityIndicatorVisible = YES;
    

    这会将状态栏的活动指示器设置为“开启”。 加载完成后,您需要再次将其关闭。这样做:

    UIApplication* app = [UIApplication sharedApplication];
    app.networkActivityIndicatorVisible = NO;
    

    如果您一次下载的文件不超过一个,那么只需将这两行添加到您的 connectionDidFinisLoadingdidFailWithError 方法实现中。

    【讨论】:

    • 我担心连接仍在后台工作。谢谢你:)
    • 如果您收到对这些方法之一的调用,那肯定不是。
    • 理论上你可以并行触发多个连接。对于它们中的每一个,将调用其中一个方法。
    【解决方案2】:

    在 start 方法中,放置你的函数方法:

    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    

    ...最后,放入connectionDidFinisLoadingconnectiondidFailWithError

    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    

    希望这会有所帮助!

    【讨论】:

      【解决方案3】:

      你可以用这条简单的线隐藏它

        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
      

      【讨论】:

        猜你喜欢
        • 2012-11-25
        • 1970-01-01
        • 2010-09-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多