如何让iPhone 4 LED瞬间点亮?

cgo*_*ain 9 iphone flashlite ios4

我目前正在使用以下代码打开和关闭我的iPhone 4 LED灯,它工作得很好,但唯一的问题是,每次我打开LED时都会有轻微的延迟.然而,它立即关闭.我需要它立即启动以实现类似频闪的功能,因为它更方便.

我注意到,在Apple的相机应用程序和许多其他应用程序中,当您按下电源按钮时,LED会立即打开和关闭.

我已经尝试将一些像"session"和"device"这样的对象作为实例变量添加到我的视图控制器中,以便iPhone在加载时创建这些对象,但是我没有任何运气让它工作.

我也试过看苹果WWDC示例代码,但我似乎无法破译他们复杂的代码.有人可以帮我解决这个问题,我已经尝试了大约4天才能让这个工作.

.H

#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>

@interface FlashlightViewController : UIViewController {

    AVCaptureSession *torchSession;
}

@property (nonatomic, retain) AVCaptureSession * torchSession;

- (void) toggleTorch;

@end
Run Code Online (Sandbox Code Playgroud)

.M

#import "FlashlightViewController.h"

@implementation FlashlightViewController

@synthesize torchSession;

- (void)dealloc 
{
    [torchSession release];
    [super dealloc];
}

- (void)viewDidLoad 
{
    [self toggleTorch];
    [super viewDidLoad];
}

- (void) toggleTorch 
{
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];

    if ([device hasTorch] && [device hasFlash])
    {
        if (device.torchMode == AVCaptureTorchModeOff) 
        {
            NSLog(@"It's currently off.. turning on now.");

            AVCaptureDeviceInput *flashInput = [AVCaptureDeviceInput deviceInputWithDevice:device error: nil];
            AVCaptureVideoDataOutput *output = [[AVCaptureVideoDataOutput alloc] init];

            AVCaptureSession *session = [[AVCaptureSession alloc] init];

            [session beginConfiguration];
            [device lockForConfiguration:nil];

            [device setTorchMode:AVCaptureTorchModeOn];
            [device setFlashMode:AVCaptureFlashModeOn];

            [session addInput:flashInput];
            [session addOutput:output];

            [device unlockForConfiguration];

            [output release];

            [session commitConfiguration];
            [session startRunning];

            [self setTorchSession:session];
            [session release];
        }
        else {

            NSLog(@"It's currently on.. turning off now.");
            [torchSession stopRunning];
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

hot*_*aw2 30

在应用初始化或查看加载期间,在要打开闪光灯LED之前,执行除闪存配置块之外的所有操作(所有会话和设备配置).

然后,当您想要打开LED时,只需设置手电筒模式.就像是:

[self.myDevice lockForConfiguration:nil];
[self.myDevice setTorchMode:AVCaptureTorchModeOn];
[self.myDevice setFlashMode:AVCaptureFlashModeOn];
[self.myDevice unlockForConfiguration];
Run Code Online (Sandbox Code Playgroud)

确保在init期间myDevice是一个正确配置的属性.