Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/three.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 在Swift中向通知中添加if语句_Ios_Swift_Timer_Notifications_Alert - Fatal编程技术网

Ios 在Swift中向通知中添加if语句

Ios 在Swift中向通知中添加if语句,ios,swift,timer,notifications,alert,Ios,Swift,Timer,Notifications,Alert,现在,当应用程序加载时,我的代码会立即显示一条警告消息。我想将代码更改为仅显示警报消息。如果在加载后20秒内未按下按钮。按钮操作称为按按钮 import UIKit class ViewController: UIViewController { let myNotification = Notification.Name(rawValue:"MyNotification") override func viewDidLoad() { super.viewDidLoad()

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

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)
}}

将您的警报代码包装在一个不重复的
计时器中,延迟20秒。在您的
按钮
功能中,在该计时器上调用
无效
,以禁止显示通知

在离开视图控制器时(例如,在
viewWillDisapear
方法中),使计时器失效可能是一个好主意