Search code examples
iosobjective-cdownloadbackground-process

Run code in the background


I'm trying to download an image from a website and save it as a UIImage but if the user has low connection this can take forever... how can I download it in the background so the user can keep using the app in the meantime?

here is the code:

theIcon.image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://myWebsite.com/Icon.png"]]];

Solution

  • Use GCD.

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
        // do my background code
        dispatch_async(dispatch_get_main_queue(), ^{
            // do handling on main thread when done!
        });
    });