1, first introduce avfoundation.framework frame
2. h file
Add #import <AVFoundation/AVFoundation.h>
@interface Lightviewcontroller:uiviewcontroller
{
BOOL Islighton;
Avcapturedevice *device;
}
@property BOOL Islighton;
@end
3. m file
#import "LightViewController.h"
@interface Lightviewcontroller ()
@end
@implementation Lightviewcontroller
@synthesize Islighton;
-(ID) Initwithnibname: (NSString *) Nibnameornil Bundle: (nsbundle*) Nibbundleornil
{
self = [super InitWithNibName:nibNameOrNilbundle:nibBundleOrNil];
if (self) {
Self.navigationItem.title = @ "Flashlight";
}
return self;
}
-(void) viewdidload
{
[Super Viewdidload];
UIButton *btn = [Uibuttonbuttonwithtype:uibuttontyperoundedrect];
[Btn Setframe:cgrectmake (80, 150, 100, 80)];
[Btn addtarget:self Action: @selector (btnclicked) forcontrolevents:uicontroleventtouchupinside];
[Self.view ADDSUBVIEW:BTN];
Avcapturedevice represents an abstract hardware device
To find a suitable avcapturedevice
device = [Avcapturedevicedefaultdevicewithmediatype:avmediatypevideo];
if (![ Device Hastorch]) {//Determine if there is a flash
Uialertview *alter = [[uialertviewalloc]initwithtitle:@] Prompt "message:@" The current device does not have a flash and cannot provide a flashlight function "Delegate:nil cancelbuttontitle:@ "Cancel" otherbuttontitles:nil, nil];
[Alter show];
[Alter release];
}
Islighton = NO;
}
-(void) btnclicked
{
Islighton = 1-islighton;
if (Islighton) {
[Self turnonled:yes];
}else{
[Self turnoffled:yes];
}
}
Turn on the flashlight
-(void) turnonled: (BOOL) update
{
[Device Lockforconfiguration:nil];
[Device Settorchmode:avcapturetorchmodeon];
[Device unlockforconfiguration];
}
Turn off the flashlight
-(void) turnoffled: (BOOL) update
{
[Device Lockforconfiguration:nil];
[Device Settorchmode:avcapturetorchmodeoff];
[Device unlockforconfiguration];
}
IOS Flashlight Code and understanding