【问题标题】:NSURLConnection Delegation with Separate ThreadNSURLConnection 委托与单独的线程
【发布时间】:2012-09-26 18:34:37
【问题描述】:

我使用MBProgressHUD 作为指标。你知道它在执行其他方法时使用了一个单独的线程。当我想使用NSURLConnection时,它的委托没有正确调用。

这是我所拥有的(@implementation 文件):

- (void)viewDidLoad {
    [super viewDidLoad];
    [self hudShowWithLabel];
}

-(void)hudShowWithLabel {
    HUD = [[MBProgressHUD alloc] initWithView: self.view];
    [self.view addSubview:HUD];

    HUD.delegate = self;
    HUD.labelText = @"Loading";
    [HUD showWhileExecuting:@selector(myTask) onTarget:self withObject:nil animated:YES];
}

-(void)myTask {
    responseData = [NSMutableData data];
    NSLog(@"Is%@ main thread", ([NSThread isMainThread] ? @"" : @" NOT"));
    NSString *requestURL = @"http://someurl";

    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:requestURL]];
    (void)[[NSURLConnection alloc] initWithRequest:request delegate: self];    
}

在运行时,我可以看到myTask 不在MainThread 中。我该如何解决这个问题?

【问题讨论】:

    标签: nsurlconnection nsurlconnectiondelegate


    【解决方案1】:

    你可以在主线程中启动 NSURLConnection:

    [self performSelectorOnMainThread:@selector(start) withObject:nil waitUntilDone:YES];
    

    而选择器开始是:

    - (void)start
    {
        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:requestURL]];
    
        self.connection =[[NSURLConnection alloc] initWithRequest:request
                                                     delegate:self
                                             startImmediately:NO];
        [self.connection scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
        [self.connection start];
    }
    

    github上也有一个例子。

    【讨论】:

      【解决方案2】:

      NSURLConnection 在另一个应该有运行循环的线程中运行。您可以尝试在线程的 main 方法中添加这样的运行循环代码:

      while (!finished)
      {
        [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:1]];
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-04-11
        • 1970-01-01
        • 1970-01-01
        • 2011-09-27
        • 2012-07-13
        • 2013-08-24
        相关资源
        最近更新 更多