سؤال

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.

هل كانت مفيدة؟

المحلول

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

نصائح أخرى

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

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

}

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)
}

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

Swift 4

func deviceHasTorch() -> Bool {
    return AVCaptureDevice.default(for: AVMediaType.video)?.hasTorch == true
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top