Detect phone calls on iOS with CTCallCenter (Swift)

前端 未结 2 1855
栀梦
栀梦 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:11

    callEventHandler has been deprecated starting iOS 10.

    iOS 10 now employs a new framework to accomplish what you are trying to do, CallKit. This is Apple's new framework that should handle all phone call interruptions. To detect incoming and outgoing calls you use the CXCallObserver. This class uses a protocol CXCallObserverDelegate to inform a registered delegate of a change in calls. I have found that it works well setting AppDelegate as the delegate.

    // AppDelegate
    var callObserver: CXCallObserver!
    
    // in applicationDidFinishLaunching...
    callObserver = CXCallObserver()
    callObserver.setDelegate(self, queue: nil) // nil queue means main thread
    
    extension AppDelegate: CXCallObserverDelegate {
        func callObserver(_ callObserver: CXCallObserver, callChanged call: CXCall) {
            if call.hasEnded == true {
                print("Disconnected")
            }
            if call.isOutgoing == true && call.hasConnected == false {
                print("Dialing")
            }
            if call.isOutgoing == false && call.hasConnected == false && call.hasEnded == false {
                print("Incoming")
            }
    
            if call.hasConnected == true && call.hasEnded == false {
                print("Connected")
            }
        }
    }
    
    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题