找到startStopAction:并在该方法中调用上面的方法:
- (IBAction)startStopAction:(id)sender
{
if (!self.isReading) {
[self startScanning];
[self.view bringSubviewToFront:self.toolBar];
[self.startStopButton setTitle:@"Stop"];
}
else {
[self stopScanning];
[self.startStopButton setTitle:@"Start"];
}
self.isReading = !self.isReading;
}
至此,二维码扫描相关的代码已经完成,如果想要它能够正常运行的话,还需要在Info.plist文件中添加NSCameraUsageDescription键及相应描述以访问相机:

需要注意的是,现在只能扫描二维码但是还不能读取到二维码中的内容,不过我们可以连接设备,运行试下:

2.3.2 读取二维码
读取二维码需要实现AVCaptureMetadataOutputObjectsDelegate协议的captureOutput:didOutputMetadataObjects:fromConnection:方法:
- (void)captureOutput:(AVCaptureOutput *)output didOutputMetadataObjects:(NSArray<__kindof AVMetadataObject *> *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
if (metadataObjects != nil && metadataObjects.count > 0) {
AVMetadataMachineReadableCodeObject *metadataObject = metadataObjects.firstObject;
if ([[metadataObject type] isEqualToString:AVMetadataObjectTypeQRCode]) {
NSString *message = [metadataObject stringValue];
[self performSelectorOnMainThread:@selector(displayMessage:) withObject:message waitUntilDone:NO];
[self performSelectorOnMainThread:@selector(stopScanning) withObject:nil waitUntilDone:NO];
[self.startStopButton performSelectorOnMainThread:@selector(setTitle:) withObject:@"Start" waitUntilDone:NO];
self.isReading = NO;
}
}
}
- (void)displayMessage:(NSString *)message
{
UIViewController *vc = [[UIViewController alloc] init];
UITextView *textView = [[UITextView alloc] initWithFrame:vc.view.bounds];
[textView setText:message];
[textView setFont:[UIFont preferredFontForTextStyle:UIFontTextStyleBody]];
textView.editable = NO;
[vc.view addSubview:textView];
[self.navigationController showViewController:vc sender:nil];
}
在这里我们将扫码结果显示在一个新的视图中,如果你运行程序的话应该可以看到扫描的二维码内容了。
另外,为了使我们的应用更逼真,可以在扫描到二维码信息时让它播放声音。这首先需要在项目中添加一个音频文件:










