Tuesday, December 1, 2015

How to ON/OFF flashlight with one button in iOS


Turn ON/OFF Flashlight in iOS

Objective

How to turn ON/OFF camera flashlight in iOS, this is our main objective. There are so many users; those are using turn on flashlight with one button and turn off flashlight with another. But here I want to do it with a single button only.

Follow the below mentioned step in order to implement flash light in iOS:


Step-1 :- First of all create xCode project named it FlashLightDemo and saved it. This                          project will  contain one View Controller, which will become main view controller. 

Step-2 :- To implement flash light we required AVFoundation framework. The AVFoundation framework is responsible for management and interaction with audio-visual media in iOS applications. AVFoundation framework needs to link to your application. For that go to project, now select build Phases tab, and then go to Link Binary with Library, Add framework as following.

Step-3 :-Code for Flashing

Write following function to the tap event of above mentioned button.


- (IBAction)btnFlashOnClicked:(id)sender
{
    
    AVCaptureDevice *flashLight = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];

    if ([flashLight isTorchAvailable] &&                [flashLight isTorchModeSupported:AVCaptureTorchModeOn])
    {
        BOOL success = [flashLight lockForConfiguration:nil];
        if (success)
        {
            if ([flashLight isTorchActive])
            {
                [btnFlash setTitle:@"TURN ON" forState:UIControlStateNormal];
                [flashLight setTorchMode:AVCaptureTorchModeOff];
            }
            else
            {
                [btnFlash setTitle:@"TURN OFF" forState:UIControlStateNormal];
                [flashLight setTorchMode:AVCaptureTorchModeOn];
            }
            [flashLight unlockForConfiguration];
        }
    }
    else{
        NSLog(@"Torch not found in Simulator");
    }
}


I hope you found this blog helpful while working Flashlight with one button. Let me know if You have any question or concerns regarding iOS, Please put a comment here and i will get back to you in short time.

No comments:

Post a Comment