我正在调用一个功能试图打开我的设备闪光灯:
private func flashOn(device:AVCaptureDevice)
{
print("flashOn called");
do {
try device.lockForConfiguration()
// line below returns warning 'flashMode' was deprecated in iOS 10.0: Use AVCapturePhotoSettings.flashMode instead.
device.flashMode = AVCaptureDevice.FlashMode.auto
device.unlockForConfiguration()
} catch {
// handle error
print("flash on error");
}
}
将device.flashMode设置为AVCaptureDevice.FlashMode.auto会显示警告"' flashMode'在iOS 10.0中已弃用:请改用AVCapturePhotoSettings.flashMode。"。虽然它只是一个警告,但它在测试我的应用时没有启用闪存,因此我将该行更改为:
device.flashMode = AVCaptureDevice.FlashMode.auto
所以我按照它的建议设置了这一行:
AVCapturePhotoSettings.flashMode = AVCaptureDevice.FlashMode.auto
我收到错误"实例成员' flashMode'不能用于类型' AVCapturePhotoSettings'"
所以我不知道如何使用Swift 4.0在Xcode版本9中设置闪存。我在Stack Overflow中找到的所有答案都适用于以前的版本。
答案 0 :(得分:8)
我一直面临同样的问题。不幸的是,许多有用的方法在iOS10和11中被弃用了。以下是我设法解决它的方法:
AVCapturePhotoSettings对象是唯一的,无法重复使用,因此每次使用此方法都需要获取新设置:
/// the current flash mode
private var flashMode: AVCaptureDevice.FlashMode = .auto
/// Get settings
///
/// - Parameters:
/// - camera: the camera
/// - flashMode: the current flash mode
/// - Returns: AVCapturePhotoSettings
private func getSettings(camera: AVCaptureDevice, flashMode: AVCaptureDevice.FlashMode) -> AVCapturePhotoSettings {
let settings = AVCapturePhotoSettings()
if camera.hasFlash {
settings.flashMode = flashMode
}
return settings
}
如您所见,不需要lockConfiguration。
然后在拍摄照片时使用它:
@IBAction func captureButtonPressed(_ sender: UIButton) {
let settings = getSettings(camera: camera, flashMode: flashMode)
photoOutput.capturePhoto(with: settings, delegate: self)
}
希望它会有所帮助。
答案 1 :(得分:2)
对于目标C:
- (IBAction)turnTorchOn: (UIButton *) sender {
sender.selected = !sender.selected;
BOOL on;
if (sender.selected) {
on = true;
}
else{
on = false ;
}
// check if flashlight available
Class captureDeviceClass = NSClassFromString(@"AVCaptureDevice");
if (captureDeviceClass != nil) {
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
AVCapturePhotoSettings *photosettings = [AVCapturePhotoSettings photoSettings];
if ([device hasTorch] && [device hasFlash]){
[device lockForConfiguration:nil];
if (on) {
[device setTorchMode:AVCaptureTorchModeOn];
photosettings.flashMode = AVCaptureFlashModeOn;
//torchIsOn = YES; //define as a variable/property if you need to know status
} else {
[device setTorchMode:AVCaptureTorchModeOff];
photosettings.flashMode = AVCaptureFlashModeOn;
//torchIsOn = NO;
}
[device unlockForConfiguration];
}
}
}