简单使用
#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>
#import <SafariServices/SafariServices.h> // iOS9新增
@interface ViewController ()<AVCaptureMetadataOutputObjectsDelegate>
@property (nonatomic, strong) AVCaptureDeviceInput *deviceInput;
@property (nonatomic, strong) AVCaptureMetadataOutput *metadataOutput;
@property (nonatomic, strong) AVCaptureSession *session;
@property (nonatomic, strong) AVCaptureVideoPreviewLayer *previewLayer;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
self.deviceInput = [[AVCaptureDeviceInput alloc] initWithDevice:device error:nil];
self.metadataOutput = [[AVCaptureMetadataOutput alloc] init];
self.session = [[AVCaptureSession alloc] init];
if ([self.session canAddInput:self.deviceInput]) {
[self.session addInput:self.deviceInput];
}
if ([self.session canAddOutput:self.metadataOutput]) {
[self.session addOutput:self.metadataOutput];
}
[self.metadataOutput setMetadataObjectTypes:@[
AVMetadataObjectTypeQRCode
]];
[self.metadataOutput setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
self.previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.session];
self.previewLayer.frame = self.view.bounds;
[self.view.layer addSublayer:self.previewLayer];
[self.session startRunning];
}
#pragma mark - AVCaptureMetadataOutputObjectsDelegate 代理方法
- (void)captureOutput:(AVCaptureOutput *)captureOutput
didOutputMetadataObjects:(NSArray *)metadataObjects
fromConnection:(AVCaptureConnection *)connection {
[self.session stopRunning];
[self.previewLayer removeFromSuperlayer];
for (AVMetadataMachineReadableCodeObject *object in metadataObjects) {
NSLog(@"二维码内容: %@",object.stringValue);
if ([object.stringValue hasPrefix:@"http"]) {
SFSafariViewController *safariVC = [[SFSafariViewController alloc]
initWithURL:[NSURL URLWithString:object.stringValue]];
[self presentViewController:safariVC animated:YES completion:nil];
}
}
}