离开(segue)时如何关闭火炬?

时间:2014-09-08 13:37:19

标签: ios objective-c

我制作了一款利用Torch的应用程序。我有一个按钮可以打开/关闭火炬。但是,如果用户打开手电筒,则导航远离视野,手电筒保持打开状态。用户必须导航回查看才能关闭。我想要的是当用户离开页面时火炬自动关闭。

使用Xcode 5.1.1; IOS 7;这个应用程序主要用于iPhone

以下是我用于Torch的代码:

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController
@synthesize btnFlash;

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

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

- (IBAction)btnFlashOnClicked:(id)sender
{
    AVCaptureDevice *flashLight = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    if ([flashLight isTorchAvailable] && [flashLight     isTorchModeSupported:AVCaptureTorchModeOn])
    {
        BOOL success = [flashLight lockForConfiguration:nil];
        if (success)
        {
            if ([flashLight isTorchActive])
            {
                [btnFlash setTitle:@"Light On" forState:UIControlStateNormal];
                [flashLight setTorchMode:AVCaptureTorchModeOff];
            }
            else
            {
                [btnFlash setTitle:@"Light Off" forState:UIControlStateNormal];
                [flashLight setTorchMode:AVCaptureTorchModeOn];
            }
            [flashLight unlockForConfiguration];
        }
    }
}


@end

2 个答案:

答案 0 :(得分:1)

好的,将功能分解为允许轻松查询当前灯状态的方法以及打开或关闭它的方法:

- (AVCaptureDevice *)flashLight
{
    AVCaptureDevice *flashLight = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    if (![flashLight isTorchAvailable] ||
        ![flashLight isTorchModeSupported:AVCaptureTorchModeOn]) {
        flashLight = nil;
    }
    return flashLight;
}

- (BOOL)isLightOn
{
    BOOL isOn = NO;
    AVCaptureDevice *flashLight = [self flashLight];
    if ([flashLight lockForConfiguration:nil]) {
        isOn = [flashLight isTorchActive];
        [flashLight unlockForConfiguration];
    }
    return isOn;
}

- (void)turnLightOn:(BOOL)on
{
    AVCaptureDevice *flashLight = [self flashLight];
    if ([flashLight lockForConfiguration:nil]) {
        [flashLight setTorchMode:on ? AVCaptureTorchModeOn : AVCaptureTorchModeOff];
        [flashLight unlockForConfiguration];
    }
}

因为这样可以更轻松地简单地调用turnLightOn:NO,无论当前状态如何,并且更容易在您的操作方法中进行操作:

- (IBAction)btnFlashOnClicked:(id)sender
{
    BOOL newState = ![self isTorchOn];
    [self turnLightOn:newState];
    [btnFlash setTitle:newState ? @"Light Off" : @"Light On"
              forState:UIControlStateNormal];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self turnLightOn:NO];
}

答案 1 :(得分:0)

您可以在方法内关闭手电筒:

- (void)viewDidDisappear:(BOOL)animated

只需在视图控制器中粘贴以下内容:

- (void)viewDidDisappear:(BOOL)animated{

[super viewDidAppear:animated];

// your code to turn the torch off goes here

}