Search code examples
iosswiftavcapturesession

Apple's AVCamera photo capture


I'm trying to use this: https://developer.apple.com/library/content/samplecode/AVCam/Introduction/Intro.html

I'm trying to access the photoData after the photo has been taken so I can upload it to a server.

When the capture button is pressed, a ton of setup code gets run, and then this is called at the very bottom:

self.photoOutput.capturePhoto(with: photoSettings, delegate: photoCaptureDelegate)

photoCaptureDelegate is another file that comes along with the project, and inside of that is this:

func capture(_ captureOutput: AVCapturePhotoOutput, didFinishProcessingPhotoSampleBuffer photoSampleBuffer: CMSampleBuffer?, previewPhotoSampleBuffer: CMSampleBuffer?, resolvedSettings: AVCaptureResolvedPhotoSettings, bracketSettings: AVCaptureBracketedStillImageSettings?, error: Error?) {
        if let photoSampleBuffer = photoSampleBuffer {
            photoData = AVCapturePhotoOutput.jpegPhotoDataRepresentation(forJPEGSampleBuffer: photoSampleBuffer, previewPhotoSampleBuffer: previewPhotoSampleBuffer)
            print("Got photo Data...this is where I want to capture/use the data")

        }
        else {
            print("Error capturing photo: \(error)")
            return
        }
    }

So in this photoCaptureDelegate "photoData" is getting set to a jpeg of whatever picture is being taken. I'm wanting to then be able to use that data back in the view controller the capturePhoto button is so I can upload it to the server using functions I've got defined in the main view controller.

How do I grab that photo data and use it back in the other viewcontroller that called the self.photoOutput.capturePhoto?

Alternatively..would it be bad practice to just run the posting to server code from directly inside of the didFinishProcessingPhoto? I could make it so I had access to the variables I need from inside there, but this seems incorrect.


Solution

  • There is no need to do that in the delegate.

    In the call, in CameraViewController, when you create the PhotoCaptureDelegate (line 533), it has 3 callbacks, being the last one completed, in that code you receive the photoCaptureDelegate responsible of the photo and in it you have your code, so you can do what you want there

    completed: { [unowned self] photoCaptureDelegate in
        //Save capture here. Image data is in here
        //photoCaptureDelegate.photoData
        self.sessionQueue.async { [unowned self] in                  
            self.inProgressPhotoCaptureDelegates[photoCaptureDelegate.requestedPhotoSettings.uniqueID] = nil
        }
    }