0

I have an ios app that has a tab button for opening camera and another button for opening photo album. They open the first time just fine, but if you cancel or go to another tab, camera and photo album won't open the second time.

As an example, here's the photo album view controller. Only thing I changed is viewDidLoad method and adding openPhotoAlbum method. I used storyboard to add tabs.

PhotoAlbumViewController.m

#import "PhotoAlbumViewController.h"
#import "AppDelegate.h"

@interface PhotoAlbumViewController ()

@property (nonatomic, strong) AppDelegate *appDelegate;

@end

@implementation PhotoAlbumViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    [self openPhotoAlbum];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (IBAction)openPhotoAlbum
{
    UIImagePickerController *albumPicker = [[UIImagePickerController alloc] init];

    albumPicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;

    albumPicker.delegate = self;

    [self presentViewController:albumPicker animated:YES completion:nil];
}

@end

step 1: i click Album

step 2: photo album shows up the first time

step 3: cancel

step 4: photo album doesn't show up

Jason Kim
  • 18,102
  • 13
  • 66
  • 105

1 Answers1

0

With a tab bar controller managing your hierarchy, your view controller will get created the first time you select them. When they are created, viewDidLoad will be called.

Once they are created, the will hang around and will re-appear when you select their tab again.

A better choice would be to use viewWillAppear which is called both on the first creation (after viewDidLoad) and on every subsequent appearance of the UIViewController.

- (void)viewDidLoad
{
//called only on initial creation and appearance
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)viewWillAppear:(BOOL)animated
{
//called on every appearance
    [super viewWillAppear:animated];
    [self openPhotoAlbum];
}

Here is a good SO answer for understanding the lifecycle of UIViewController

Community
  • 1
  • 1
HalR
  • 11,411
  • 5
  • 48
  • 80