AVCaptureVideoPreviewLayer (camera preview) freezes/stuck after moving to background and back

后端 未结 6 656
忘了有多久
忘了有多久 2020-12-15 20:38

Cant figure this one out. Everything works fine when the app is active, and than sometimes when i move the app to the background(pressing the home button) a

6条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-15 20:59

    I think that there are different things that could cause the problem:

    1. You should wrap all the configuration that you are doing in a -beginConfiguration and -commitConfiguration block of code. Each time you setup something in the session it will takes time to do it. Wrapping your configuration code between those method will guarantee that all the changes are committed in one shot, reducing the overall session creation time
    2. Pausing the session is a good when you go to the background. Register your class as an observer to UIApplicationDidEnterBackground and UIApplicationWillEnterForeground to pause and start again the session.
    3. You create the session in -viewWillAppear each time this method is called you create a session but, is not really clear from your code if you get rid of it. You should separate and balance the session creation and destroy. Provide a -setupSession and a -tearDownSession methods. Make sure that the setup is called only if there is no active session and make sure that when you don't need the session anymore you get rid of it by calling the teardownSession. In SWIFT you na use a @lazy variable and destroy the session in deinit() or -viewWillDisappear.
    4. It could be very useful to create or use a SYNC queue creating and destroying a session is an intensive task and you usually prefer to put it on a background queue, furthermore helps to synchronize all the methods that involve the session. Creating your own sync queue will guarantee for example the sync between a setup session call and tear down call, one is called only when the other one finish.

    I undestand that is huge refactor, but I'm this way I'm pretty sure that you will experience less problems in the future.

提交回复
热议问题