在iOS 7中测试新的条形码扫描api时遇到问题。此示例(单 View 应用程序)工作正常,但我想停止AVCaptureSession并在相机识别出EAN码后显示第一个 View 。[self.captureSession startRunning];
不起作用。
如何正确停止AVCaptureSession?
#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>
@interface ViewController () <AVCaptureMetadataOutputObjectsDelegate>
@property (strong) AVCaptureSession *captureSession;
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.captureSession = [[AVCaptureSession alloc] init];
AVCaptureDevice *videoCaptureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
NSError *error = nil;
AVCaptureDeviceInput *videoInput = [AVCaptureDeviceInput deviceInputWithDevice:videoCaptureDevice error:&error];
if(videoInput)
[self.captureSession addInput:videoInput];
else
NSLog(@"Error: %@", error);
AVCaptureMetadataOutput *metadataOutput = [[AVCaptureMetadataOutput alloc] init];
[self.captureSession addOutput:metadataOutput];
[metadataOutput setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
[metadataOutput setMetadataObjectTypes:@[AVMetadataObjectTypeQRCode, AVMetadataObjectTypeEAN13Code]];
AVCaptureVideoPreviewLayer *previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.captureSession];
previewLayer.frame = self.view.layer.bounds;
[self.view.layer addSublayer:previewLayer];
[self.captureSession startRunning];
}
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
for(AVMetadataObject *metadataObject in metadataObjects)
{
AVMetadataMachineReadableCodeObject *readableObject = (AVMetadataMachineReadableCodeObject *)metadataObject;
if([metadataObject.type isEqualToString:AVMetadataObjectTypeQRCode])
{
NSLog(@"QR Code = %@", readableObject.stringValue);
}
else if ([metadataObject.type isEqualToString:AVMetadataObjectTypeEAN13Code])
{
NSLog(@"EAN 13 = %@", readableObject.stringValue);
}
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
最佳答案
您实际上可以停止AVCaptureSession从而:
[self.captureSession stopRunning];
但是我怀疑您真正想做的是卡住屏幕。在属性中保留对您的PreviewLayer的引用很有帮助。然后:
[[self.previewLayer connection] setEnabled:NO];
您可以尝试执行类似操作来卡住屏幕,然后在几秒钟后将其解冻
- (void) captureOutput:(AVCaptureOutput *)captureOutput
didOutputMetadataObjects:(NSArray *)metadataObjects
fromConnection:(AVCaptureConnection *)connection
{
[[self.previewLayer connection] setEnabled:NO];
double delayInSeconds = 2.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW,
(int64_t)(delayInSeconds * NSEC_PER_SEC));
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
[[self.previewLayer connection] setEnabled:YES];
});
...
}
更新
完整移除:
[self.captureSession stopRunning];
[self.previewLayer removeFromSuperlayer];
self.previewLayer = nil;
self.captureSession = nil;
关于iOS正确停止AVCaptureSession,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20746413/