问题
Hi i am using a location based app and wants to use iphone camera flashlight while in background.Unfortunately flashlight is working only in foreground ,it automatically turns off the flash in background even though the code is executing .
The code i used is working only in foreground
#import <AVFoundation/AVFoundation.h>
//flashcode
Class captureDeviceClass = NSClassFromString(@"AVCaptureDevice");
if (captureDeviceClass != nil) {
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
if ([device hasTorch] && [device hasFlash]){
[device lockForConfiguration:nil];
if (device.torchMode == AVCaptureTorchModeOff)
{
[device setTorchMode:AVCaptureTorchModeOn];
[device setFlashMode:AVCaptureFlashModeOn];
//torchIsOn = YES;
}
else
{
[device setTorchMode:AVCaptureTorchModeOff];
[device setFlashMode:AVCaptureFlashModeOff];
// torchIsOn = NO;
}
[device unlockForConfiguration];
}
}
回答1:
This is a normal behavior.
Apple's sandboxing will not allow you to keep the flash on while your app is in the background.
There is no workaround unless we are talking about a jailbroken app.
Edit:
Apple is very strict on it's system's APIs usage. Especially when it comes to:
- User privacy
- Battery life
- User experience
In the case of the flashlight, the last two items are relevant. Apple will not let an app drain the battery when not in the foreground and iOS users are used to the fact that flashlight, camera, microphone... are immediately disabled when going to the background (with an exception for the microphone in some background modes cases).
To answer the comment on your initial post, iOS controls your hardware. So since Apple decided they don't want the light to stay on when the user closes the app, iOS will just power off the flash when your app goes in the background. Your app has no authority to prevent it.
来源:https://stackoverflow.com/questions/32136442/iphone-flashlight-not-working-while-app-is-in-background