WatchOS 7.1 WKLongPressGesture detected, alert presented, but action closures not firing

Viewed 60

I am trying to implement a WKLongPressGestureRecognizer in my app. The long press gesture is recognized and the alert it presented. However, when I select the option to clear the table (I'm using Realm), the alert controller is dismissed, but the take is not cleared. When I tried to debug by adding breakpoints in the code, it seemed that the code inside the closure was being skipped completely. Any idea what I'm missing? (Should I be using an action sheet sided of an alert sheet?) I've tried so many different things. Here's the code with the print statements that I've been using to debug. None of the print statements inside the closures are currently being triggered.

@IBAction func handleLongPress(_ sender: Any) {

print("long press pressed")

WKInterfaceDevice.current().play(.click)

let clearAction = WKAlertAction(title: "Clear", style: .destructive) {
    print("clear button pressed")
}

let cancelAction = WKAlertAction(title: "Cancel", style: .default) {
    print("cancel button pressed")
}

presentAlert(withTitle: "Are you sure?", message: "Action cannot be undone", preferredStyle: .alert, actions: [clearAction, cancelAction])

print("exiting long press")}

Thanks for any input or advice.

1 Answers

The gesture recognizer will call selector handleLongPress twice, once with state == began, and once with state cancelled. I found that this causes the problems with presentAlert that you're describing.

Try checking for the began state:

@IBAction func handleLongPress(_ sender: WKGestureRecognizer) {
    guard sender.state == .began else {
        return
    }
    // rest of handleLongPress implementation goes here
}

This should ensure your alert is presented exactly once.

Related