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
This is an extension on my comment above.
Try making
callCenter
a property of your view controller instead of just a variable inviewDidLoad
.
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