iossdwebimagembprogresshud

SDWebImage + MBProgressHUD


Good day!

I use these two libraries when download full sized images from web.

CODE:

-(void)viewDidAppear:(BOOL)animated
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^
    {
        [imageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@", img]] placeholderImage:[UIImage imageNamed:@"stub_image.jpg"]];

    dispatch_async(dispatch_get_main_queue(), ^
    {
      [MBProgressHUD hideHUDForView:self.view animated:YES];
    });
});

It turns out that the full size picture is loaded later than hiding the indicator (shown placeholder image)

What I do wrong?


Solution

  • On your code, the line

    [MBProgressHUD hideHUDForView:self.view animated:YES];
    

    is executed before the download has finished.

    The method sd_setImageWithURL:placeholderImage: is non-blocking thread.

    You should use the completionBlock of sd_setImageWithURL:placeholderImage:completed: and adding your hiding method into.

    Using blocks

    With blocks, you can be notified about the image download progress and whenever the image retrieval has completed with success or not:

    Note: neither your success nor failure block will be call if your image request is canceled before completion.

    Try this code :

    -(void)viewDidAppear:(BOOL)animated
    {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^ {
                    [imageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@", img]] placeholderImage:[UIImage imageNamed:@"stub_image.jpg"]
                                completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL)
                        {
                            dispatch_async(dispatch_get_main_queue(), ^ {
                                [MBProgressHUD hideHUDForView:self.view animated:YES];
                            });
            }];
        });
    }