Search code examples
iosswiftphone-callnotificationcenter

get a notification from notificationCenter after returning from a phone call


I want to do an action after the user tapped on the call button and made a call then returned to the app.

This is my function for making a phone call :

let phoneURL = URL(string: String(format: "tel://%@", phoneNumber.englishNumbers))
UIApplication.shared.open(phoneURL!)

and I have set an observer on CallView in viewDidLoad() like this:

NotificationCenter.default.addObserver(self, selector: #selector (showFeedBack), name: UIApplication.didEnterBackgroundNotification, object: nil)

After I made the call and pressed on the End button (the red button which ends the call). the CallView would appear but the notification won't get called.

Am I using the right notification? or is this the correct approach for detecting when a user made a phone call through your app and came back?

P.S. I have used willResignActiveNotification notification. but it send the notification before even making the call (when the alert is appeared and the user has not select anything yet)


Solution

  • You can use CXCallObserver to listen the call events as below,

    import CallKit
    
    class ViewController: UIViewController, CXCallObserverDelegate {
    
        let co = CXCallObserver()
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            co.setDelegate(self, queue: DispatchQueue.main)
        }
    
        func callObserver(_ callObserver: CXCallObserver, callChanged call: CXCall) {
            if call.hasEnded {
                print("Call is ended")
            }
            if call.hasEnded == false && call.hasConnected {
                print("Call is connected")
            }
            if call.isOutgoing {
                print("This is an outgoing call")
            } else if call.hasEnded == false && call.hasConnected == false {
                print("This is an incoming call")
            }
        }
    }