Asynchronous Image Loading with Activity Indicator Animation using GCD in viewDidLoad

Loading Images Asynchronously in viewDidLoad with Activity Indicator

As developers, we’ve all been there - trying to display a new view after a long-running task has completed. In this scenario, we often face the challenge of balancing performance and user experience. In this article, we’ll explore how to load images asynchronously in viewDidLoad while displaying an activity indicator animation.

Understanding the Problem

When loading images synchronously, our app becomes unresponsive, and the user is left waiting for the image to be fetched. On the other hand, when using asynchronous loading, we risk showing a blank view before the images have finished being loaded.

Our goal is to achieve a balance between these two approaches: allowing the app to remain responsive while still displaying an activity indicator animation during the loading process.

Using GCD for Asynchronous Image Loading

One popular approach to solving this problem involves using Grand Central Dispatch (GCD), a high-performance threading system provided by Apple. In this section, we’ll explore how to use GCD to load images asynchronously in viewDidLoad while displaying an activity indicator animation.

Creating a Custom Queue

To start loading our image asynchronously, we need to create a custom queue using GCD. This queue will be responsible for managing the asynchronous image loading process.

dispatch_queue_t imageLoadingQueue = dispatch_queue_create("imageLoadingQueue", NULL);

In this example, we’re creating a new queue with the name "imageLoadingQueue" and specifying that it shouldn’t have any additional properties.

Dispatching the Loading Task

Once our custom queue is created, we can dispatch a task to load the image asynchronously. We’ll use dispatch_async to schedule the task for execution on the queue.

dispatch_async(imageLoadingQueue, ^{
    // Image loading code here
});

In this example, we’re dispatching a block of code that will be executed on our custom queue.

Loading the Image

Inside the dispatched block, we’ll load the image using NSData and create a UIImage object from it.

NSString *urlString = // your URL string here
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlString]];
UIImage *image = [UIImage imageWithData:imageData];

Here, we’re loading the image by constructing a URL string and using dataWithContentsOfURL: to load the image data.

Stopping the Activity Indicator

Once the image has been loaded, we need to stop the activity indicator animation and place the image in our view.

dispatch_async(dispatch_get_main_queue(), ^{
    // Stop loading spinner here and place image in view
});

In this example, we’re dispatching another block of code that will be executed on the main queue. Inside this block, we’ll stop the activity indicator animation by removing it from our view.

Putting It All Together

Now that we’ve explored the individual components involved in loading images asynchronously with an activity indicator animation using GCD, let’s put them all together to see how it works.

dispatch_queue_t imageLoadingQueue = dispatch_queue_create("imageLoadingQueue", NULL);
// Start the loading spinner here

dispatch_async(imageLoadingQueue, ^{
    NSString *urlString = // your URL string here
    NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlString]];
    UIImage *image = [UIImage imageWithData:imageData];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        // Stop loading spinner here and place image in view
    });
});

In this example, we’re creating a custom queue, dispatching the loading task, and loading the image asynchronously. Once the image has been loaded, we’re stopping the activity indicator animation and placing the image in our view.

Real-World Example

To demonstrate how to use GCD for asynchronous image loading with an activity indicator animation, let’s consider a real-world example. Suppose we have a table view that allows users to select an image to display. When the user selects an image, we want to load the image asynchronously in viewDidLoad while displaying an activity indicator animation.

Here’s some sample code to illustrate this:

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Create a custom queue for image loading
    dispatch_queue_t imageLoadingQueue = dispatch_queue_create("imageLoadingQueue", NULL);
    
    // Start the loading spinner here
    [self.activityIndicator startAnimating];
    
    // Dispatch the image loading task
    dispatch_async(imageLoadingQueue, ^{
        NSString *urlString = [self.imageURLString stringValue];
        NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlString]];
        UIImage *image = [UIImage imageWithData:imageData];
        
        // Stop loading spinner here and place image in view
        dispatch_async(dispatch_get_main_queue(), ^{
            self.activityIndicator.stopAnimating();
            [self ImageView setImage:image];
        });
    });
}

// Sample properties
@property (nonatomic, strong) NSString *imageURLString;
@property (nonatomic, strong) UIImageView *ImageView;
@property (nonatomic, strong) UIActivityIndicatorView *activityIndicator;

// Sample methods
- (void)setImageUrlString:(NSString *)imageURLString {
    _imageURLString = imageURLString;
}

- (UIImageView *)ImageView {
    if (_ImageView == nil) {
        _ImageView = [[UIImageView alloc] init];
    }
    return _ImageView;
}

- (UIActivityIndicatorView *)activityIndicator {
    if (_activityIndicator == nil) {
        _activityIndicator = [[UIActivityIndicatorView alloc] initWithStyle:UIActivityIndicatorStyleWhiteAndBlack];
    }
    return _activityIndicator;
}

In this example, we’re creating a custom queue for image loading and dispatching the loading task using dispatch_async. We’re also loading the image asynchronously and stopping the activity indicator animation once the image has been loaded.

Conclusion

Loading images asynchronously in viewDidLoad while displaying an activity indicator animation is a useful technique for improving user experience. By using GCD, we can create custom queues to manage asynchronous tasks and ensure that our app remains responsive while still providing visual feedback to the user.

By following the steps outlined in this article, you should be able to implement GCD-based image loading with an activity indicator animation in your own iOS projects. Remember to always prioritize performance and user experience when building apps - and don’t hesitate to reach out if you have any further questions or need additional guidance!


Last modified on 2025-03-25