Iphone flashlight not working while app is in background
Asked Answered
T

1

7

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];
    }
}
Thanatos answered 21/8, 2015 at 9:3 Comment(2)
It would be good if someone explains how apples sandboxing kills the flashlight when app is in backgroundThanatos
I edited my answer to explain a bit more.Pearly
P
12

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:

  • 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 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.

Pearly answered 21/8, 2015 at 9:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.