开发者

How to consume UI Events while loading data in the background

I have a little iPhone app that loads data from a web service. To make sure that nothing goes wrong while loading the data I create a semi-transparent view over the app and use CFRunloopRun() to wait until all the data is loaded in the background. This is the code for that:

        self.connection = [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];

    // Now show an animation
    UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    UIView *window = [[UIApplication sharedApplication] keyWindow];
    UIView *shield = [[UIView alloc] initWithFrame:window.bounds];
    shield.backgroundColor = [UIColor blackColor];
    shield.alpha = 开发者_运维问答0.5f;
    [window addSubview:shield];
    spinner.center = shield.center;
    [shield addSubview:spinner];
    spinner.hidden = NO;
    NSLog( @"JCL.callServerWithRequest(), spinner view: %@, shield view: %@, window: %@", spinner, shield, window );
    [spinner startAnimating];

    // Hand over to the Runnloop to wait
    CFRunLoopRun();

    [spinner stopAnimating];
    [spinner removeFromSuperview];
    [spinner release];
    [shield removeFromSuperview];
    [shield release];

This works fine except that any clicks on a button somewhere is played after the loading so if the users clicks on the download button twice he will do the download twice as well.

Any idea how to consume the UI events before the shield is removed.

Thanks - Andy


Try it without messing with runloops. I suspect that the UI events are coming in to the normal loop on the window but not being processed until your custom loop returns, at which point the "shield" view is no longer there to catch them. If you put the shield in place and then let the main runloop handle things, the shield should catch them all as normal.


Thanks to Anomie I finally tried out to go without the CFRunLoopRun() and it is quite difficult because the execution is split into two parts: - the Invocation and the Return of the Result through a callback. But then I shot myself in the proverbial foot because I tried to block the returning thread to slow down the execution which did not work because that was executed again in the main thread.

Eventually I did slow down the Web Service and then everything worked as expected.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜