How can I determine whether my iOS device has a to

2019-02-25 00:36发布

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.

6条回答
爷的心禁止访问
2楼-- · 2019-02-25 01:18

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
查看更多
老娘就宠你
3楼-- · 2019-02-25 01:18

Swift 4

func deviceHasTorch() -> Bool {
    return AVCaptureDevice.default(for: AVMediaType.video)?.hasTorch == true
}
查看更多
ら.Afraid
4楼-- · 2019-02-25 01:24

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)
}
查看更多
倾城 Initia
5楼-- · 2019-02-25 01:26

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

}

查看更多
对你真心纯属浪费
6楼-- · 2019-02-25 01:29

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

查看更多
在下西门庆
7楼-- · 2019-02-25 01:38

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

查看更多
登录 后发表回答