如何在 WatchOS 的基于页面的界面中显示警报?

How to display an alert in page based interface on WatchOS?

我的手表应用程序有一个基于页面的界面,我真的不知道屏幕上当前有什么 InterfaceController(可能是 4 个中的 1 个),但是无论应用程序在哪个屏幕上,我都需要弹出警报在。如果我不一定知道哪个 InterfaceController "current?",我该如何显示警报 如果用户导航到此 InterfaceController,下面的代码只会 运行。如果用户不在该页面上,那么我会在控制台中看到此错误 2019-09-22 15:42:01.597663-0400 Watch Extension[501:526217] Warning: Attempt to present <PUICAlertSheetController: 0x18158c00> on <SPInterfaceViewController: 0x1795e800> whose view is not in the window hierarchy!

extension WorkoutControlsInterfaceController: WorkoutEndedDelegate {
    func timerEndedCheckToSeeIfWorkoutEnded(_ manager: WorkoutManager) {
        let endWorkoutAction = WKAlertAction(title: "End Workout", style: .default, handler: {
            print("User has selected to end the workout")
            self.workoutManager?.stopWorkout()

        })
        let cancelAction = WKAlertAction(title: "Cancel", style: .cancel, handler: {

        })
        self.becomeCurrentPage()
        self.presentAlert(withTitle: "Workout Ended?", message: "It looks like your workout may have ended?", preferredStyle: .alert, actions: [endWorkoutAction, cancelAction])
    }


}

您可以使用共享 WKExtesion 对象中的 visibileInterfaceController 属性;

extension WorkoutControlsInterfaceController: WorkoutEndedDelegate {
    func timerEndedCheckToSeeIfWorkoutEnded(_ manager: WorkoutManager) {
        let endWorkoutAction = WKAlertAction(title: "End Workout", style: .default, handler: {
            print("User has selected to end the workout")
            self.workoutManager?.stopWorkout()

        })
        let cancelAction = WKAlertAction(title: "Cancel", style: .cancel, handler: {

        })

        WKExtension.shared().visibleInterfaceController?.presentAlert(withTitle: "Workout Ended?", message: "It looks like your workout may have ended?", preferredStyle: .alert, actions: [endWorkoutAction, cancelAction])
    }


}