4

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.

Martin Gordon
  • 36,329
  • 7
  • 58
  • 54
Yuvaraj.M
  • 9,741
  • 16
  • 71
  • 100

6 Answers6

4

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

The Windwaker
  • 1,054
  • 12
  • 24
4

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

Martin Gordon
  • 36,329
  • 7
  • 58
  • 54
3

Swift 4

var deviceHasTorch: Bool {
    return AVCaptureDevice.default(for: AVMediaType.video)?.hasTorch == true
}
Jess
  • 1,394
  • 12
  • 12
1

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

}

Andrew Cook
  • 116
  • 1
  • 8
0

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)
}
M-P
  • 4,909
  • 3
  • 25
  • 31
0

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
Awesomeness
  • 652
  • 1
  • 8
  • 14