问题
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.
回答1:
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
回答2:
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
回答3:
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];
}
}
回答4:
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)
}
回答5:
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
回答6:
Swift 4
var deviceHasTorch: Bool {
return AVCaptureDevice.default(for: AVMediaType.video)?.hasTorch == true
}
来源:https://stackoverflow.com/questions/8418293/how-can-i-determine-whether-my-ios-device-has-a-torch-light