ios - swift : take photo from AVFoundation

标签 ios swift avfoundation

我想将此函数从 obj c 转换为 swift,但我无法转换部分代码。 有人可以向我解释如何从 AVFondation 拍照或帮助我翻译此功能吗?

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

我做了什么但没有工作:

  func takePhoto(sender:UIButton){

  var videoConnection:AVCaptureConnection
  var connection:AVCaptureConnection
   var port : AVCaptureInputPort

 for connection in stillImageOutput?.connections {

for (port in connection.inputPorts as AVCaptureInputPort) {


    if port = AVMediaTypeVideo {
        videoConnection = connection
        break
    }

}

    if videoConnection {
        break
   }


 }
stillImageOutput?.captureStillImageAsynchronouslyFromConnection(videoConnection,      completionHandler: {(imageSampleBuffer, error) in
if (imageSampleBuffer != nil) {
    var imageData =      AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(imageSampleBuffer as CMSampleBuffer)
    var image: UIImage = UIImage(data: imageData)


}
})


}

有人可以帮我吗?

最佳答案

由于上面的代码不起作用,我在 Swift 中找到了一个优雅的解决方案。

取而代之的是:

var videoConnection : AVCaptureConnection?
for connection in self.stillImageOutput.connections{
    for port in connection.inputPorts!{
        if port.mediaType == AVMediaTypeVideo{
            videoConnection = connection as? AVCaptureConnection
            break //for ports
        }
    }
    if videoConnection != nil{
        break //for connections
    }
}//take a photo then

你应该使用这个:(针对“输出”拼写错误进行了更新)

if let videoConnection = stillImageOutput.connectionWithMediaType(AVMediaTypeVideo){//take a photo here}

希望对您有所帮助!

关于ios - swift : take photo from AVFoundation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25871513/

相关文章:

swift - UIPageViewController多次加载ChildViews

ios - 使用 Alamofire 解析 Codable 响应

ios - 通过 IBAction (Objective-C) 直接发送短信

iphone - 手动将屏幕旋转到横向,屏幕左侧会留下一个白色条,旧状态栏所在的位置

ios - ARC 语义问题 "multiple methods named ' setRotation'“仅在归档时

ios - 使字符串中的文本与同一字符串中的其他文本不同?

ios - 如何预加载来自 Web 链接的 mp3 流

ios - AVAudioEngine 停止设备的背景音频

ios - 将音频与视频完美融合

ios - 将前置摄像头与 AVFoundation 一起使用时,闪光灯不起作用