在输入背景模式时关闭UIImagePickerController

时间:2014-03-31 02:33:54

标签: ios objective-c uiimagepickercontroller

我使用UIImagePickerController在我的项目中使用Camera和Camera Roll。

这是我的示例代码

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

[self presentViewController:picker animated:YES completion:NULL];

它有效,但如果我想在进入后台模式时解雇它。 如何解决它。

谢谢你,对不起我的英语。

2 个答案:

答案 0 :(得分:3)

您可以使用UIApplicationDidEnterBackgroundNotification收听NSNotificationCenter通知。

有了这个,您可以设置一个方法,只要应用程序进入后台,您就可以检查是否正在显示选择器(可能会在显示时存储对它的引用):

- (void)presentImagePicker
{
    if (self.displayedPicker) {
        return;
    }

    self.displayedPicker = [[UIImagePickerController alloc] init];
    self.displayedPicker.delegate = self;
    self.displayedPicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;

    [self presentViewController:self.displayedPicker animated:YES completion:nil];

    // Register for the method to be called every time the app enters the background
    [[NSNotificationCenter defaultCenter]
        addObserver:self
        selector:@selector(didEnterBackgroundNotification:)
        name:UIApplicationDidEnterBackgroundNotification
        object:nil
    ];
}

- (void)dismissImagePickerAnimated:(BOOL)animated
{
    if (self.displayedPicker) {
        [self.displayedPicker dismissViewControllerAnimated:animated];
        self.displayedPicker = nil;

        // Unregister from notification
        [[NSNotificationCenter defaultCenter]
            removeObserver:self
            name:UIApplicationDidEnterBackgroundNotification
            object:nil
        ];
    }
}

- (void)didEnterBackgroundNotification:(NSNotification *)notification
{
    [self dismissImagePickerAnimated:NO];
}

答案 1 :(得分:0)

您必须在班级中设置UIImagePickerController属性。在你的AppDelegate类中,你可以实现applicationDidEnterBackground:Method,你可以这样做:

[yourViewController.picker dismissModalViewControllerAnimated:YES];

如果您的应用进入后台,则应该关闭ImagePicker。希望这有助于.. :))