我在 swift 中使用 AVFoundation 来拍照,但我无法将任何功能代码行从 objective c 转换为 Swift。我的函数代码是:
- (void) capImage { //method to capture image from AVCaptureSession video feed
AVCaptureConnection *videoConnection = nil;
for (AVCaptureConnection *connection in stillImageOutput.connections) {
for (AVCaptureInputPort *port in [connection inputPorts]) {
if ([[port mediaType] isEqual:AVMediaTypeVideo] ) {
videoConnection = connection;
break;
}
}
if (videoConnection) {
break;
}
}
NSLog(@"about to request a capture from: %@", stillImageOutput);
[stillImageOutput captureStillImageAsynchronouslyFromConnection:videoConnection completionHandler: ^(CMSampleBufferRef imageSampleBuffer, NSError *error) {
if (imageSampleBuffer != NULL) {
NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageSampleBuffer];
[self processImage:[UIImage imageWithData:imageData]];
}
}];
这一行向我发送错误 AnyObject[]does not conform to protocol sequencfe..:
for (AVCaptureInputPort *port in [connection inputPorts]) {
swift :
for port:AnyObject in connection.inputPorts {
我不知道如何转换这一行:
[stillImageOutput captureStillImageAsynchronouslyFromConnection:videoConnection completionHandler: ^(CMSampleBufferRef imageSampleBuffer, NSError *error) {
你能帮我转换成swift吗? 谢谢!!
最佳答案
for (AVCaptureInputPort *port in [connection inputPorts]) { )
AnyObject
的数组应该在交互之前转换为您的实际类型的数组,如下所示:
for (port in connection.inputPorts as AVCaptureInputPort[]) { }
就 block 到闭包而言,您只需确保语法正确即可。
stillImageOutput.captureStillImageAsynchronouslyFromConnection(videoConnection) {
(imageSampleBuffer, error) in // This line defines names the inputs
//...
}
请注意,这也使用了 Trailing Closure Syntax .请多阅读文档!
编辑:就初始化器而言,它们现在看起来像这样:
let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(imageSampleBuffer)
self.processImage(UIImage(data:imageData))
关于camera - 如何将代码 AVFoundation objective c 转换为 Swift?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24288048/