3

I'm using MBProgressHUD as an indicator. And you know it's using a separate thread when while executing some other method. When I want to use NSURLConnection, its delegation is not calling properly.

Here what I have (@implementation file):

- (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];    
}

While running, I can see that myTask is not in MainThread. How could I solve this problem?

2 Answers2

2

You can kick off NSURLConnection in the main thread:

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

And the the selector start is:

- (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];
}

There is also an example on github.

hrchen
  • 1,223
  • 13
  • 17
0

NSURLConnection runs in another thread which should have a run loop. You could try to add code for run loop like this in your thread's main method:

while (!finished)
{
  [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:1]];
}
Richard
  • 339
  • 3
  • 10