Detect phone calls on iOS with CTCallCenter (Swift)

萝らか妹 提交于 2019-12-01 04:03: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

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")
        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!