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 synchronous
and 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];
}
});
}
这样处理,就不会卡住主线程了。