首页 > 解决方案 > 如何创建通知触发器?[迅速]

问题描述

如何创建触发器以仅在变量小于某个值时触发通知?

public static var updateElap = Int() // This is the variable I am checking

override func viewDidAppear(_ animated: Bool) {

    NotificationCenter.default.addObserver(self, selector: #selector(appWentInBackground), name: .UIApplicationDidEnterBackground, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(appWillEnterForeground), name: .UIApplicationWillEnterForeground, object: nil)
}

@objc func appWentInBackground(){
    beginDate = Date()
    focusTimer.invalidate()
    print(updateElap)
    print("background")

    /** Notification **/

    let content = UNMutableNotificationContent()
    content.title = "blah"
    content.body = "blah"
    content.badge = 1

     // This is where I need to set the notification
     // if updateElap < blah blah {fire notification} else {blah blah}
     // It's basically a notification inside a notification

}

@objc func appWillEnterForeground() {
    runProdTimer()
    endDate = Date()
    secondsPassedInBackground = endDate.timeIntervalSince(beginDate) // Double
    print(beginDate)
    print(endDate)
    print(secondsPassedInBackground)
    updateElap = updateElap + Int(secondsPassedInBackground)
    print(updateElap)
    print("foreground")
    intBrSeconds = intBrSeconds - Int(secondsPassedInBackground) // Updated Break Time after user returns to the app aka foreground
    breakSession.text = brTimeString(bTime: TimeInterval(intBrSeconds))

}

有没有办法使用 UNMutableNotificationContent() 、 UNNotificationRequest() 和 UNUserNotificationCenter() 来实现这一点?

标签: iosswifttriggersuilocalnotification

解决方案


var myVariable = 1 {
    didSet {
        if myVariable > blah blah {
            //add notification
        }
    }
}

在上述情况下,只要您的 myVariable 值符合给定标准,您就会收到通知。

更新:您必须didSelect在声明实际 myVariable 的位置设置此属性。


推荐阅读