4

在我的应用程序中,我可以选择手电筒。然而,只有 iPhone 4 和 iPhone 4S 有手电筒。其他设备没有手电筒。如何找到当前的设备型号?请帮我。提前致谢。

4

6 回答 6

4

您不应将设备型号用作是否存在某项功能的指标。相反,请使用能够准确告诉您该功能是否存在的 API。

在您的情况下,您想使用AVCaptureDevice'-hasTorch属性:

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

AV Foundation Programming GuideAVCaptureDevice Class Reference中提供了更多信息

于 2011-12-07T16:06:46.350 回答
3

与上面的代码相比,您可以使用更少的代码并使用更少的内存:

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

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

hasTorch 现在将包含正确的值

于 2014-06-12T12:23:50.727 回答
2

斯威夫特 4

var deviceHasTorch: Bool {
    return AVCaptureDevice.default(for: AVMediaType.video)?.hasTorch == true
}
于 2018-12-10T09:57:55.613 回答
1

此代码将使您的设备能够打开手电筒。但它也会检测手电筒是打开还是关闭并执行相反的操作。

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

}

于 2015-07-02T04:38:15.300 回答
0

斯威夫特 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)
}
于 2017-11-03T00:43:57.660 回答
0

devicesWithMediaType:现在已弃用。

斯威夫特 4:

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

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

return false
于 2018-04-24T16:09:07.263 回答