Kishor Kundan
Kishor Kundan

Reputation: 3165

How to shift operation from main queue to background releasing the main queue

This is what I am doing.

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);

dispatch_async(queue, ^{
    NSData* data = [NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://myurl"]]];
    dispatch_sync(dispatch_get_main_queue(), ^{
        if(!data) {
            // data not recieved or bad data. Initiate reachability test
            // I have built a wrapper for Reachability class called ReachabilityController
            // ReachabilityController also notifies the user for avaibility, UI 

            ReachabilityController *reachability = [[ReachabilityController alloc] init];
            [reachability checkReachability];
            return;
        }
        //update table
    });
});

My problem is the reachability test is being done in the main queue, which often freezes the UI. I want to run in a background mode.

I want to process the ReachabilityTest in a background mode or in a low priority mode. But again, my reachability controller does notify user of the current net avaibility, so at some point i will have to use main queue again.

I strongly believe that there must be a better way.

Upvotes: 0

Views: 297

Answers (1)

Ismael
Ismael

Reputation: 3937

This is, however, a correct way. It doesn't look entirely pretty, but that doesn't mean it's incorrect. If you want your code to look 'cleaner' you might wanna take a look at NSThread and work your way through it, but this is a far easier approach.

To make it look easier in my project we made a simple class called dispatcher that uses blocks:

+ (void)dispatchOnBackgroundAsync:(void(^)(void))block {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), block);
}

+ (void)dispatchOnMainAsync:(void(^)(void))block {
    dispatch_async(dispatch_get_main_queue(), block);
}

used like this:

[Dispatcher dispatchOnBackgroundAsync:^{
    // background thread code

    [Dispatcher dispatchOnMainAsync:^{
        // main thread code
    }];
}];

Upvotes: 1

Related Questions