Search code examples
objective-cios7avcapturesession

How to add 'cancel' button to camera acquisition code?


I have this code which captures a barcode; it works fine, except on an iPad, if you can't/don't hold the iPad steady, it "tries until the cows come home" if you get my drift. I want to add a "cancel" button or figure out some way to cancel the method so I don't have to kill the app and start it again. Here is my code:

- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection  {

CGRect highlightViewRect = CGRectZero;
AVMetadataMachineReadableCodeObject *barCodeObject;
NSString *detectionString = nil;
NSArray *barCodeTypes = @[AVMetadataObjectTypeEAN13Code];

for (AVMetadataObject *metadata in metadataObjects) {
    for (NSString *type in barCodeTypes) {
        if ([metadata.type isEqualToString:type])
        {
            barCodeObject = (AVMetadataMachineReadableCodeObject *)[_prevLayer transformedMetadataObjectForMetadataObject:(AVMetadataMachineReadableCodeObject *)metadata];
            highlightViewRect = barCodeObject.bounds;
            detectionString = [(AVMetadataMachineReadableCodeObject *)metadata stringValue];
            break;
        }
    }

    if (detectionString != nil)  {
        _label.text = detectionString;
        oISBNField.text = detectionString;  //  move detectionString to ISBN textbox
        [_session stopRunning];
        [_prevLayer removeFromSuperlayer];
        [_label removeFromSuperview];

        break;
    }
    else
        _label.text = @"(none)";
}

}

Can someone please give me some help on this? I would really, really appreciate it! :D


Solution

  • Just create a cancel button and add it to the UIViewController's view.

    When the button is pressed, stop the capture session and dismiss the presented view controller.

    - (void)cancelButtonPressed:(id)sender {
        [self.captureSession stopRunning]; //stop the capture session
        [self.presentingViewController dismissViewControllerAnimated:YES completion:nil]; // dismiss the current view controller
    }