これはSwift 4.2用のiOS 10+ソリューションで、iOS 12 でテストされており、[キャンセル] ボタンと [通話] ボタンの両方を検出します。
CallKit をインポートして、クラスを に準拠させることを忘れないでくださいCXCallObserverDelegate
!
let callObserver = CXCallObserver()
var didDetectOutgoingCall = false
func showCallAlert() {
guard let url = URL(string: "tel:+36201234567"),
UIApplication.shared.canOpenURL(url) else {
return
}
callObserver.setDelegate(self, queue: nil)
didDetectOutgoingCall = false
//we only want to add the observer after the alert is displayed,
//that's why we're using asyncAfter(deadline:)
UIApplication.shared.open(url, options: [:]) { [weak self] success in
if success {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
self?.addNotifObserver()
}
}
}
}
func addNotifObserver() {
let selector = #selector(appDidBecomeActive)
let notifName = UIApplication.didBecomeActiveNotification
NotificationCenter.default.addObserver(self, selector: selector, name: notifName, object: nil)
}
@objc func appDidBecomeActive() {
//if callObserver(_:callChanged:) doesn't get called after a certain time,
//the call dialog was not shown - so the Cancel button was pressed
DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) { [weak self] in
if !(self?.didDetectOutgoingCall ?? true) {
print("Cancel button pressed")
}
}
}
func callObserver(_ callObserver: CXCallObserver, callChanged call: CXCall) {
if call.isOutgoing && !didDetectOutgoingCall {
didDetectOutgoingCall = true
print("Call button pressed")
}
}