Ios 如何正确停止AVCaptureSession

Ios 如何正确停止AVCaptureSession,ios,avcapturesession,Ios,Avcapturesession,我正在做一个iOS应用程序,需要验证QR码,层次结构如下: View ---Scan View ---Image View - cardBG ---Inside View 加载视图时,扫描视图将隐藏 当用户点击按钮进行扫描时,内部视图和图像视图被设置为隐藏,显示扫描视图 扫描返回成功后,内部和图像再次出现 问题出在第3步:当我停止AVCaptureSession时,即使是在异步调度中,如,刷新视图也需要8-10秒 dispatch\u async(dispatch\u get\u global

我正在做一个iOS应用程序,需要验证QR码,层次结构如下:

View
---Scan View
---Image View - cardBG
---Inside View
  • 加载视图时,扫描视图将隐藏
  • 当用户点击按钮进行扫描时,内部视图和图像视图被设置为隐藏,显示扫描视图
  • 扫描返回成功后,内部和图像再次出现
  • 问题出在第3步:当我停止AVCaptureSession时,即使是在异步调度中,如,刷新视图也需要8-10秒

    dispatch\u async(dispatch\u get\u global\u queue(dispatch\u queue\u PRIORITY\u DEFAULT,0)^{
    如果([\u captureSession正在运行][\u captureSession停止运行];
    AVCaptureInput*input=[\u captureSession.inputs对象索引:0];
    [\u captureSession removeInput:input];
    AVCaptureVideoDataOutput*输出=(AVCaptureVideoDataOutput*)[\u captureSession.outputs对象索引:0];
    [\u captureSession removeOutput:output];
    });
    [self.bgImageView setHidden:否];
    [self.insideView setHidden:否];
    [self.scanView setHidden:是];
    [self.previewLayer从SuperLayer移除];
    

    我的问题是:如何获得视图以避免冻结?

    没有更多上下文,很难说。取决于实际导致延迟的原因。你喜欢这个工作吗

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        if([_captureSession isRunning])[_captureSession stopRunning];
    
        dispatch_async(dispatch_get_main_queue(), ^{
          [self.bgImageView setHidden:NO];
          [self.insideView setHidden:NO];
          [self.scanView setHidden:YES];
          [self.previewLayer removeFromSuperlayer];        
        });
    
        AVCaptureInput* input = [_captureSession.inputs objectAtIndex:0];
        [_captureSession removeInput:input];
        AVCaptureVideoDataOutput* output = (AVCaptureVideoDataOutput*)[_captureSession.outputs objectAtIndex:0];
        [_captureSession removeOutput:output];    
    
    });
    

    以下代码将帮助您:

    if(self.previewLayer) {
        [self.previewLayer removeFromSuperlayer];
        self.previewLayer = nil;
    }
    
    if(_captureSession) {
        [_captureSession stopRunning];
        _captureSession = nil;
    }
    

    也许你能通过这个帖子找到你的答案,谢谢。这对我也有帮助。原因是我试图在不在主线程中时更新UI。