Yuvaraj.M
Yuvaraj.M

Reputation: 9801

How can I determine whether my iOS device has a torch light?

In my application I have the option for a torch light. Howevver, only iPhone 4 and iPhone 4S have torch lights. Other devices do not have the torch light. How can I find the current device model? Please help me. Thanks in advance.

Upvotes: 4

Views: 3579

Answers (6)

Jess
Jess

Reputation: 1394

Swift 4

var deviceHasTorch: Bool {
    return AVCaptureDevice.default(for: AVMediaType.video)?.hasTorch == true
}

Upvotes: 3

Awesomeness
Awesomeness

Reputation: 651

devicesWithMediaType: is now deprecated.

Swift 4:

let discoverySession = AVCaptureDevice.DiscoverySession(deviceTypes: [.builtInWideAngleCamera], mediaType: .video, position: .back)

for device in discoverySession.devices {
    if device.hasTorch {
        return true
    }
}

return false

Upvotes: 0

M-P
M-P

Reputation: 4959

Swift 4

if let device = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo) {
    if (device.hasTorch) {
        // Device has torch
    } else {
        // Device does not have torch
    }
} else {
    // Device does not support video type (and so, no torch)
}

Upvotes: 0

Andrew Cook
Andrew Cook

Reputation: 116

This code will give your device the ability to turn on the flashlight. But it will also detect if the flashlight is on or off and do the opposite.

- (void)torchOnOff: (BOOL) onOff {

AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
if ([device hasTorch]) {
    [device lockForConfiguration:nil];
    if (device.torchMode == AVCaptureTorchModeOff) {
        device.torchMode = AVCaptureTorchModeOn;
        NSLog(@"Torch mode is on.");
    } else {
        device.torchMode = AVCaptureTorchModeOff;
        NSLog(@"Torch mode is off.");
    }
    [device unlockForConfiguration];
}

}

Upvotes: 1

The Windwaker
The Windwaker

Reputation: 1054

You can have less code and use less memory than the code above:

NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
BOOL hasTorch = NO;

for (AVCaptureDevice *device in devices) {
    if ([device hasTorch]) {
        hasTorch = YES;
        break;
    }
}

hasTorch will now contains the correct value

Upvotes: 4

Martin Gordon
Martin Gordon

Reputation: 36389

You should not use the device model as an indicator of whether a feature is present. Instead, use the API that tells you exactly if the feature is present.

In your case, you want to use AVCaptureDevice's -hasTorch property:

NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
NSMutableArray *torchDevices = [[NSMutableArray alloc] init];
BOOL hasTorch = NO;

for (AVCaptureDevice *device in devices) {
    if ([device hasTorch]) {
        [torchDevices addObject:device];
    }
}

hasTorch = ([torchDevices count] > 0);

More information is available in the AV Foundation Programming Guide and the AVCaptureDevice Class Reference

Upvotes: 4

Related Questions