一段时间后如何显示 UIAlertView?

How to display UIAlertView after some time?

我试图在一段时间后显示 UIAlertView(比如在应用程序中执行某些操作后 5 分钟)。如果应用程序已关闭或处于后台,我已经通知用户。但是我想在应用程序 运行 时显示一个 UIAlertView。我不想一次又一次地刷新。三分钟后,我必须显示一些提示,比如你要保存还是不保存?

使用

self.perform(#selector(displayAlert), with: nil, afterDelay: 300)

其中显示警报是显示警报的函数。

我认为对于具有自定义延迟的 UIAlertView,还有另一种最佳方法是您可以根据需要使用 timeInterval 安排本地通知。

终于,我找到了问题的答案: 我正在使用带有以下代码的点击手势:

func displayAlert()
    {
        let alert = UIAlertController(title: "My Title", message: "This is my message.", preferredStyle: UIAlertControllerStyle.alert)

        // add an action (button)
        alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))

        // show the alert
        self.present(alert, animated: true, completion: nil)
        self.timer = NSTimer.scheduledTimerWithTimeInterval(50.0, target: self, selector: #selector(SONGS.displayAlert), userInfo: nil, repeats: false)

        timer.invalidate()// stop the timer
}

如果您设置 repeats:true,它将每 50 秒显示一次警报,如果您想停止计时器,您可以在任何需要的地方使用 timer.invalidate()。 谢谢

它对我有用:

self.timer = NSTimer.scheduledTimerWithTimeInterval(10.0, target: self, selector: #selector(SONGS.displayAlert), userInfo: nil, repeats: false)
func displayAlert()
{
   self.message.dismissWithClickedButtonIndex(0,animated: true)
}