Ios 在Swift中向通知中添加if语句
现在,当应用程序加载时,我的代码会立即显示一条警告消息。我想将代码更改为仅显示警报消息。如果在加载后20秒内未按下按钮。按钮操作称为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()
按按钮
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
方法中),使计时器失效可能是一个好主意