Jannes
Jannes

Reputation: 19

Xcode load slow things after the View is visible

I have a very annoying problem. I have a ViewController with an UIImageView in it. The UIImageView should display a slide show. The images for the are coming from NSURL, so it takes a bit of time.

- (void)viewDidLoad { [super viewDidLoad]; [self loadImages]; }

This is how I get the Images from the NSURL. The problem I have is, that while the Images are loading I only see a black screen. At the beginning and at the end of the -(void)loadImages method I implemented a UIActivityIndicator to display the loading time. I already tried -(void)viewWillAppear and -(void)viewDidLayoutSubviews but nothing worked.

Thanks for help Jannes

Upvotes: 0

Views: 357

Answers (2)

Aaron Wojnowski
Aaron Wojnowski

Reputation: 6480

You're probably downloading your images synchronously. Try wrapping it in a dispatch_async block to run it on a different thread.

Example:

-(void)loadImages {

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void) {

        // download the images here

        dispatch_async(dispatch_get_main_queue(), ^(void) {

            // update the UI on the main thread

        });

    });

}

Check out the SDWebImage library as well as most of this heavy lifting is done for you.

Upvotes: 1

Reid
Reid

Reputation: 1129

What you need to do is load your images asynchronously and populate them as they come in (with delegate or block callbacks, depending on the API you use). You should absolutely never run networking code, or any other potentially long-running operation, synchronously on the main thread. The reason for this is that the UI runs on the main thread, so if you block it with your own operations, the UI cannot update and your app will become unresponsive.

Whether you're using Apple's networking frameworks or something like AFNetworking (highly recommended), there are many ways to do networking asynchronously with minimal work.

Upvotes: 1

Related Questions