现在,我的代码会在应用加载时立即显示警告消息。我想将代码更改为仅显示警报消息。如果在加载后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)
}}
答案 0 :(得分:0)
将警报代码包含在非重复Timer
内,延迟时间为20秒。在pressBUTTON
功能中,请在此类计时器上调用invalidate
以禁止显示通知。
在离开视图控制器时也可能使计时器无效(例如,在viewWillDisapear
方法中)。