1

I want something similar to C#'s BackgroundWorker.

I want to execute a block code of code (irrespective of what kind of code it is. It could be networking, I/O, complex math operations, whatever) in the background while I animate a NSProgressIndicator. Once the operation is complete, not only do I want to hide the progress indicator but I also want to receive result object(s) from the background code back to the main code.

What is the best way to do this?

Thanks for the help!

AyushISM
  • 381
  • 7
  • 21

2 Answers2

1

You may want to do some reading about NSOperation, NSOperationQueue, and blocks.

Using these you can execute your "block" of code asynchronously and have it "schedule" an update of the progress indicator on the main thread every so often. You can set a completion block (callback) to execute when the operation is complete and it can call a function to be executed on the main thread.

This article provides a nice overview of the options with small examples.

This answer provides an example for defining and using a completion block.

Community
  • 1
  • 1
Rotsiser Mho
  • 551
  • 2
  • 5
  • 19
-1

I think this library would be helpful - https://github.com/AFNetworking/AFNetworking

This library is a wrapper for Apple's API and has async tasks handled correctly. The example is shown here by Matt Thompson How to download a file and save it to the documents directory with AFNetworking? how to use API for downloading a resource from a url in background. This is just one example but most of them work in a similar manner to perform task in background without blocking Main UI thread

Eg :-

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"..."]];
AFHTTPRequestOperation *operation = [[[AFHTTPRequestOperation alloc] initWithRequest:request] autorelease];

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"filename"];
operation.outputStream = [NSOutputStream outputStreamToFileAtPath:path append:NO];

[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"Successfully downloaded file to %@", path);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];

[operation start];
Community
  • 1
  • 1
Aniket Bochare
  • 427
  • 2
  • 10