I'm rebuilding the Google Mobile Vision "Googly Eyes" demo in Swift 3. I figured almost all of it out, but I'm stuck on translating a function from Objective C to Swift.
The Objective C function in the demo view controller is:
- (AVCaptureDeviceInput *)cameraForPosition:(AVCaptureDevicePosition)desiredPosition {
BOOL hadError = NO;
for (AVCaptureDevice *device in [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo]) {
if ([device position] == desiredPosition) {
NSError *error = nil;
AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device
error:&error];
if (error) {
hadError = YES;
NSLog(@"Could not initialize for AVMediaTypeVideo for device %@", device);
} else if ([self.session canAddInput:input]) {
return input;
}
}
}
if (!hadError) {
NSLog(@"No camera found for requested orientation");
}
return nil;
}
I've translated that into the following:
func camera(for desiredPosition: AVCaptureDevicePosition) -> AVCaptureDeviceInput {
var hadError: Bool = false
for device: AVCaptureDevice in AVCaptureDevice.devices(withMediaType: AVMediaTypeVideo) { // ERROR ON THIS LINE
if device.position() == desiredPosition {
var error: Error? = nil
let input = try? AVCaptureDeviceInput(device: device)
if error != nil {
hadError = true
print("Could not initialize for AVMediaTypeVideo for device \(device)")
}
else if session.canAdd(input!) {
return input!
}
}
}
if !hadError {
print("No camera found for requested orientation")
}
}
The error I'm getting is on the 3rd line (for device: AVCaptureDevice in AVCaptureDevice.devices...
). The error is: 'Any' is not convertible to 'AVCaptureDevice'
. I'm not very familiar with Objective C and have never used AVCaptureSession before so I've been struggling to figure it out. Any suggestions on how I need to rewrite this "for device" statement?