Search code examples
iosmultithreadingiclouduidocument

Load document from iCloud before view will be loaded


I have images on iCloud and I subclassed UIDocument for them. Now i want to display images on the UITableView after ViewController will be loaded. So I added this code inside the viewDidLoad method

- (void)viewDidLoad    
    {
        ...
              iCloudImage *iClImage = [[iCloudImage alloc] initWithFileURL:ubiquitousPackage];
              [iClImage openWithCompletionHandler:^(BOOL success) {
                if (success) {                
                    NSLog(@"iCloud document opened");
                    dataFromFileManager = [iClImage.imageDictionary objectForKey:img.fileName];
                    imageToDraw = [[[UIImage alloc] initWithData:dataFromFileManager] autorelease];
                } else {                
                    NSLog(@"failed opening document from iCloud");    
                    imageToDraw = [UIImage imageNamed:@"defaultImage.jpg"];
                }
                [arrayOfImages addObject:imageToDraw];
            }];
        ...
    }

Here I'm collecting all images one-by-one into NSMutableArray *arrayOfImages and then using that array in the - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath method. But they are not showing in the table, because they are downloading in another thread. How can I fix that and start showing UITableView only after images are downloaded or default images set?


Solution

  • I recently had the same problem. I didn't wait to load the view until the images were downloaded, but instead displayed a progress indicator on the table. Then when the images did load, I sent an NSNotification to the view that informed it to remove the progress indicator and load the data.

    This way, you keep your UI responsive, and show the user something is actually loading. Let me know if you need me to go in any more technical detail.