-2

I am trying to show a image picker view controller from a NSObject subclass but when i call presentViewController on the app's root vc the app crashes without a error message.

My code is here:

UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;

UIViewController *root = [[[[UIApplication sharedApplication] windows] objectAtIndex:0] rootViewController];

[root presentViewController:picker animated:YES completion:nil];

If i run this in a view controller it just works fine.

EDIT:

I can't use a delegate because i am building a plugin for Unity and i can't get the view controller in other ways than this.

I noticed the crash while calling this code in the current view controller from a IBAction:

- (IBAction)showPicker:(id)sender {
    PhotoManager *manager = [[PhotoManager alloc] init];
    [manager loadPhoto];
}

In answer to the comments here's the class code:

PhotoManager.h:

@interface PhotoManager : NSObject <UINavigationControllerDelegate, UIImagePickerControllerDelegate>

- (void)loadPhoto;

@end

.m:

@implementation PhotoManager {
    UIViewController *root;
}

- (void)loadPhoto {
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;

    root = [[[[UIApplication sharedApplication] windows] objectAtIndex:0] rootViewController];

    [root presentViewController:picker animated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [root dismissViewControllerAnimated:YES completion:nil];
    NSLog(@"%@", info);
}

@end
walter-dev
  • 29
  • 1
  • 5

1 Answers1

0

The proper way would be to create a protocol / delegate and call back to the presenting viewController telling it to present the picker. This allows you to do much more and is a great habit to learn right away IMO.

How do I set up a simple delegate to communicate between two view controllers?

Community
  • 1
  • 1
Mark McCorkle
  • 9,349
  • 2
  • 32
  • 42