Detect phone calls on iOS with CTCallCenter (Swift)

前端 未结 2 1854
栀梦
栀梦 2021-01-05 08:34

I wanted to try to detect incoming phone calls in my app. I created a new Swift project from scratch just to try some code. The only thing I did was importing CoreTelephony

2条回答
  •  说谎
    说谎 (楼主)
    2021-01-05 09:14

    This is an extension on my comment above.

    Try making callCenter a property of your view controller instead of just a variable in viewDidLoad.

    When you define a variable in a method, the variable and it's value is only present within that method. When the method is finished running, the valuable and their values are clean up so they don't keep using memory (unless the value is used elsewhere).

    In your case, you define callCenter and assign it a new CTCallCenter instance. But at the end of viewDidLoad, the CTCallCenter instance is not used anymore so it is clean up from memory. Since it no longer exists, it can't handle the call events.

    By adding callCenter as a property of your view controller, it ties the lifespan of the CTCallCenter instance to the lifespan of your view controller. So the CTCallCenter will only be clean up from memory when the view controller is cleaned up from memory.

    For more detail, read Automatic Reference Counting in Swift

提交回复
热议问题