简体   繁体   中英

How to tap on UIView to capture while using mobile vision face detector

I am trying to capture still image while tap on UIView.

Project from: https://github.com/googlesamples/ios-vision

FaceDetectorDemo → FaceDetector → CameraViewController.m

I converted the Face detector project from Objective-C to Swift, but I need to add an additional feature which user tap on the screen to capture but just couldn't figure it out.

My code:

@IBOutlet weak var placeholder: UIView! 
var stillImageOutput = AVCaptureStillImageOutput()

for face in faces
{
  //somewhere in here called faceDetected() method
}

func faceDetected() -> Void
{
    let tapped = UITapGestureRecognizer(target:self,action:#selector(saveToCamera))      
    placeholder.addGestureRecognizer(tapped)
    placeholder.isUserInteractionEnabled = true
}

@objc func saveToCamera(_ sender: UIGestureRecognizer)
{
    if let videoConnection = stillImageOutput.connection(with: AVMediaType.video) {
        stillImageOutput.captureStillImageAsynchronously(from: videoConnection) {
            (imageDataSampleBuffer, error) -> Void in
            let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(imageDataSampleBuffer!)
            UIImageWriteToSavedPhotosAlbum(UIImage(data: imageData!)!, nil, nil, nil)
        }
    }
}

It doesn't seem run into the saveToCamera while tapping on the UIView .

  • The saveToCamera is not being called because when you have added placeholder.addGestureRecognizer(tap) instead of placeholder.addGestureRecognizer(tapped) , not tap but tapped
  • At selector the method mus be: saveToCamera(_:)

this is the full code. It works.

  func faceDetected() {
        let tapped = UITapGestureRecognizer(target:self,action:#selector(self.saveToCamera(_:)))
        placeholder.addGestureRecognizer(tapped)
        placeholder.isUserInteractionEnabled = true
    }



    @objc func saveToCamera(_ sender: UIGestureRecognizer) {

        if let videoConnection = stillImageOutput.connection(with: AVMediaType.video) {
            stillImageOutput.captureStillImageAsynchronously(from: videoConnection) {
                (imageDataSampleBuffer, error) -> Void in
                let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(imageDataSampleBuffer!)
                UIImageWriteToSavedPhotosAlbum(UIImage(data: imageData!)!, nil, nil, nil)
            }
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM