Search code examples
pointersswiftavcapturesession

AVCaptureSession Clean Up in Swift


I have a Swift project that's using AVCaptureSession to take photos within the app. I'm having difficulty getting the right syntax to properly clean up my objects. In Obj-C the suggested code would be as follows;

// Releases the object - used for late session cleanup
static void capture_cleanup(void* p)
{
    NewPostPreviewViewController* csc = (NewPostPreviewViewController*)p; 
    [csc release];  // releases capture session if dealloc is called
}

// Stops the capture - this stops the capture, and upon stopping completion releases self.
- (void)stopCapture {
    // Retain self, it will be released in capture_cleanup. This is to ensure cleanup is done properly,
    // without the object being released in the middle of it.
    [self retain];

    // Stop the session
    [session stopRunning];

    // Add cleanup code when dispatch queue end 
    dispatch_queue_t queue = dispatch_queue_create("VideoDataOutputQueue", NULL);
    dispatch_set_context(queue, self);
    dispatch_set_finalizer_f(queue, capture_cleanup);
    [dataOutput setSampleBufferDelegate: self queue: queue];
    dispatch_release(queue);
}

The finalizer would call capture_cleanup but I have no idea how to set the context or the pointer to the capture_cleanup function (or even what the function definition would look like)

So far I've tried the following but I'm not convinced I'm even on the right track;

let p: UnsafeMutablePointer<NewPostPreviewViewController> = UnsafeMutablePointer.alloc(sizeof(NewPostPreviewViewController))
p.initialize(self)

var videoDataOutputQueue = dispatch_queue_create("VideoDataOutputQueue", nil)
dispatch_set_context(videoDataOutputQueue, p)
dispatch_set_finalizer_f(videoDataOutputQueue, ????);
self.videoDataOutput!.setSampleBufferDelegate(self, queue: videoDataOutputQueue)
dispatch_release(videoDataOutputQueue)

Any help converting this would be most appreciated!


Solution

  • Solved using bridging to Objective-C code. By including a CameraController.m Objective-C class in my Swift project (with associated header) I bridge for access to the camera feed.

    The Objective-C class does all the work I need, and stores the last image taken. It also produces a notification once the image is taken, allowing my Swift class to observe the notification and go get the last image taken.