在Swift中向通知添加if语句

时间:2017-05-19 20:42:15

标签: ios swift timer notifications alert

现在,我的代码会在应用加载时立即显示警告消息。我想将代码更改为仅显示警报消息。如果在加载后20秒内未按下按钮。按钮操作称为pressBUTTON

import UIKit

class ViewController: UIViewController {

let myNotification = Notification.Name(rawValue:"MyNotification")

override func viewDidLoad() {
    super.viewDidLoad()

    let nc = NotificationCenter.default
    nc.addObserver(forName:myNotification, object:nil, queue:nil, using:catchNotification)
}
    @IBAction func pressBUTTON(_ sender: Any) {
    }

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    let nc = NotificationCenter.default
    nc.post(name:myNotification,
            object: nil,
            userInfo:["message":"Hello there!", "date":Date()])
}

func catchNotification(notification:Notification) -> Void {
    print("Catch notification")

    guard let userInfo = notification.userInfo,
        let message  = userInfo["message"] as? String,
        let date     = userInfo["date"]    as? Date else {
            print("No userInfo found in notification")
            return
    }

    let alert = UIAlertController(title: "Notification!",
                                  message:"\(message) received at \(date)",
        preferredStyle: UIAlertControllerStyle.alert)
    alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
    self.present(alert, animated: true, completion: nil)
}}

1 个答案:

答案 0 :(得分:0)

将警报代码包含在非重复Timer内,延迟时间为20秒。在pressBUTTON功能中,请在此类计时器上调用invalidate以禁止显示通知。

在离开视图控制器时也可能使计时器无效(例如,在viewWillDisapear方法中)。