objective-cios8backgroundcameraflashlight

Iphone flashlight not working while app is in background


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];
    }
}

Solution

  • 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 its system's APIs usage. Especially when it comes to:

    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 the flashlight, camera, and microphone are immediately disabled when going to the background (with an exception for the microphone in some background modes).

    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.