iOS 唤起相机session startRunning导致卡顿

1.苹果官方文档说明

- (void)startRunning;

Discussion

This method is used to start the flow of data from the inputs to the outputs connected to the AVCaptureSession instance that is the receiver. This method is synchronousand blocks until the receiver has either completely started running or failed to start running. If an error occurs during this process and the receiver fails to start running, you receive an AVCaptureSessionRuntimeErrorNotification

Important

The startRunning method is a blocking call which can take some time, therefore you should perform session setup on a serial queue so that the main queue isn’t blocked (which keeps the UI responsive). See AVCam-iOS: Using AVFoundation to Capture Images and Movies for an implementation example.

文档对这个方法的解释中提到了这个方法是同步方法,会阻塞当前线程,放在主线程会导致UI卡顿。

2.解决方案

/**
 *  创建一个队列,防止阻塞主线程
 */
- (void)createQueue{
    dispatch_queue_t sessionQueue = dispatch_queue_create("xxx session queue", DISPATCH_QUEUE_SERIAL);
    self.sessionQueue = sessionQueue; 
}

启动session

-(void)sessionStartRunning{

    @weakify(self);
    dispatch_async(self.sessionQueue, ^{
        @strongify(self);
        if (!self.session.running) {
            [self.session startRunning];
        }
    });
}

关闭session

-(void)sessionStopRunning{
    
    @weakify(self);
    dispatch_async(self.sessionQueue, ^{
        @strongify(self);
        if (self.session.running) {
            [self.session stopRunning];
        }
    });
}

这样处理,就不会卡住主线程了。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值