David Casillas
David Casillas

Reputation: 1911

Delay the presentation of UIAlertView until its associated viewController is displayed

I have a download running in background. It shows an UIAlertView under some fail condition.

When this alert happens, the application can be in any of the views it shows to the user, but only should be visible in one of them.

Can I delay the presentation of the UIAlertView to the moment the viewController it is associated with is displayed to the user (it's viewDidAppear method is invoked)?

Upvotes: 0

Views: 394

Answers (1)

joerick
joerick

Reputation: 16448

Declare a property on the view controller that you want to show the view.

@interface DownloadViewController : UIViewController
{
    UIAlertView *downloadAlertView;
}

@property (retain) UIAlertView *downloadAlertView;

@end

Then, when you detect the error, set the downloadAlertView property of the view controller (this will require you keeping a reference to this view controller by the object that is doing the downloading).

- (void)downloadFailed
{
    UIAlertView *alertView = [[[UIAlertView alloc] init] autorelease];
    alertView.title = @"Download Failed";
    downloadViewController.downloadAlertView = alertView;
}

Then in your DownloadViewController implementation,

- (UIAlertView *)downloadAlertView
{
    return downloadAlertView;
}

- (void)setDownloadAlertView:(UIAlertView *)aDownloadAlertView
{
    // standard setter
    [aDownloadAlertView retain];
    [downloadAlertView release];

    downloadAlertView = aDownloadAlertView;

    // show the alert view if this view controller is currently visible
    if (viewController.isViewLoaded && viewController.view.window) 
    {
         [downloadAlertView show];
         downloadAlertView = nil;
    }
}

- (void)viewDidAppear
{
    if (downloadAlertView)
    {
        [downloadAlertView show];
        downloadAlertView = nil;
    }
}

Quick explanation:

  • the first two methods are standard getter/setters, but the setter has added logic, so that if the view controller is currently visible, the alert is shown immediately.
  • if not, the alert view is stored by the view controller and shown as soon as the view appears.

Upvotes: 2

Related Questions