如何通过我的应用程序拨打电话时,用户是否按下了"呼叫"或"取消"按钮?

Dix*_*ine 8 iphone objective-c nsurl uiapplication

我需要从我的应用程序拨打电话后返回我的应用程序,所以我使用此代码:

NSURL *url = [NSURL URLWithString:@"telprompt://123-4567-890"]; 
[[UIApplication  sharedApplication] openURL:url]; 
Run Code Online (Sandbox Code Playgroud)

当用户按下按钮执行此代码时,会显示一个警告,其中包含2个按钮,"呼叫"和"取消".

如何确定用户是否按下了"呼叫"按钮?

Tam*_*gel 9

这是针对Swift 4.2iOS 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")
    }
}
Run Code Online (Sandbox Code Playgroud)


J S*_*iro 8

这并不完美,但你可以通过监听UIApplicationSuspendedNotification来识别"call"被按下而不是"取消"(当有人按下'home'键时,你必须添加一些逻辑来忽略这个事件,或者是接受来电...可能是通过在显示电话号码的逻辑周围添加/删除观察者来实现的:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(suspended:) name:@"UIApplicationSuspendedNotification" object:nil];

-(void)suspended:(NSNotification *) notification
{
    NSLog(@"Suspended");
}
Run Code Online (Sandbox Code Playgroud)

  • 正是我需要的东西,但似乎你的通知在iOS6使用中不再存在:UIApplicationDidEnterBackgroundNotification (2认同)