问题
i am trying to make an alarm app by setting new local notifications every X seconds when a Set
button is pressed and stopping when the user taps a Stop
button.
using Timer()
, i am currently able to set the local notification but it doesn't repeat as I would like. it only repeats when i go into the app and back to the previous screen via the Home
button. also, it only repeats once by doing that.
is there any way to have the user press the Set
button once and have the notifications keep firing no matter if you're in the app/outside the app and only stopping when the user presses the Stop
button?
my code as follows:
class LocalNotificationViewController: UIViewController {
var timer = Timer()
func runTimer() {
timer = Timer.scheduledTimer(timeInterval: 5, target: self, selector: (#selector(self.setLocalNotification)), userInfo: nil, repeats: true)
}
@objc func setLocalNotification() {
// timeEntered = time.text!
// let hrMin = timeEntered.components(separatedBy: ":");
let content = UNMutableNotificationContent()
content.title = "Test Local Notification"
content.subtitle = "Testing..."
content.body = "Testing..."
content.badge = 1
content.sound = UNNotificationSound(named: "alarm.aiff");
trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false);
let request = UNNotificationRequest(identifier: "timerDone", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
}
var timeEntered: String = "";
var trigger: UNTimeIntervalNotificationTrigger? = nil;
@IBOutlet var time: UITextField!;
@IBAction func setNotification(_ sender: Any) {
runTimer()
}
@IBAction func stopRepeat(_ sender: Any) {
timer.invalidate()
}
来源:https://stackoverflow.com/questions/47732363/using-timer-to-set-local-notification-every-x-seconds