0

可能重复:
如何在 viewDidLoad 上启动 iPhone 相机?

我正在尝试在我的应用程序启动时打开相机 UI。问题是,我已经使用开始按钮完成了相机应用程序,单击该开始按钮,相机被打开并用于捕捉照片和视频。

我正在尝试从 viewDidLoad 方法调用 startCameraControllerFromViewController 但我面临以下异常

警告:尝试呈现不在窗口层次结构中的视图!

这是我的代码

- (void)viewDidLoad
{

    imagePicker = [[UIImagePickerController alloc]init];
    [self startCameraControllerFromViewController: self
                                    usingDelegate: self];
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (BOOL) startCameraControllerFromViewController: (UIViewController*) controller
                                   usingDelegate: (id <UIImagePickerControllerDelegate,
                                                   UINavigationControllerDelegate>) delegate {

    if (([UIImagePickerController isSourceTypeAvailable:
          UIImagePickerControllerSourceTypeCamera] == NO)
        || (delegate == nil)
        || (controller == nil))
        return NO;

    UIImagePickerController *cameraUI = [[UIImagePickerController alloc] init];
    cameraUI.sourceType = UIImagePickerControllerSourceTypeCamera;

    cameraUI.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];

    cameraUI.allowsEditing = NO;
    cameraUI.delegate = delegate;
    [controller presentViewController: cameraUI animated: YES completion:nil];
    return YES;
}
4

1 回答 1

3

将代码放在 viewWillAppear 或 viewDidAppear 方法中可能会更好。我的猜测是,即使视图已经加载,它实际上可能还不可见,并且 startCameraControllerFromViewController 调用可能不是那样的。

只是一个猜测。

于 2013-01-24T01:36:41.360 回答