camera - 如何将代码 AVFoundation objective c 转换为 Swift?

标签 camera avfoundation swift xcode6

我在 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/

相关文章:

ios - 在 Swift 中停止和启动 NSThread

ios - 如何添加阴影平面以及苹果提供的和我们创建的.scn文件的区别

javascript - 在 THREE.js 中获取全局 'camera' 变量的值时遇到问题

opengl - 如何从相机内在矩阵计算相机的视野?

ios - 停止背景音乐

uiimage - 如何将 CIImage 转换为 CMSampleBufferRef

ios - AVFoundation - 为视频添加模糊背景

ios - 为什么我的代码不保存表中数组中的所有行?

iOS 使用摄像头和 UILongPressGestureRecognizer 录制视频

返回失败的 android 相机图片 uri 传递结果 ResultInfo