code: < /p>
import UIKit
import UserNotifications
class ViewController: UIViewController, UNUserNotificationCenterDelegate {
let eggTimes = ["Soft": 10, "Medium": 15, "Hard": 20]
var secondsRemaining = 60
var timer = Timer()
override func viewDidLoad() {
super.viewDidLoad()
// Set the notification center delegate – important for handling notifications when the app is in the foreground
UNUserNotificationCenter.current().delegate = self
// Request permission for notifications
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
if granted {
print("Notifications are enabled.")
} else {
print("Notifications are disabled.")
}
}
}
@IBAction func hardnessSelected(_ sender: UIButton) {
guard let hardness = sender.currentTitle else { return }
timer.invalidate()
secondsRemaining = eggTimes[hardness]!
// Cancel previously scheduled notifications
UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
// Schedule a new notification
scheduleNotification(after: secondsRemaining, hardness: hardness)
timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { [weak self] timer in
guard let self = self else {
timer.invalidate()
return
}
if self.secondsRemaining > 0 {
print("\(self.secondsRemaining) seconds remaining...")
self.secondsRemaining -= 1
} else {
timer.invalidate()
print("DONE!")
}
}
}
// Schedule a local notification when the timer finishes
func scheduleNotification(after seconds: Int, hardness: String) {
let content = UNMutableNotificationContent()
// Set the notification title
content.title = "The egg is done!"
// Set the notification body including the selected egg hardness
content.body = "Your \(hardness.lowercased()) egg is ready just the way you wanted!
// Set the notification sound
content.sound = UNNotificationSound.default
// Mark the notification as time-sensitive
content.interruptionLevel = .timeSensitive
// Set the trigger for the notification based on countdown duration
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: TimeInterval(seconds), repeats: false)
// Create the notification request with the above configuration
let request = UNNotificationRequest(identifier: "eggDone", content: content, trigger: trigger)
// Register the notification with the system so it can be delivered even if the app is in the background or inactive
UNUserNotificationCenter.current().add(request) { error in
if let error = error {
print("Notification error: \(error.localizedDescription)")
}
}
}
// Display notification even when the app is in the foreground (e.g., while cooking)
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler:
@escaping (UNNotificationPresentationOptions) -> Void) {
// Show banner and play sound for the notification
completionHandler([.banner, .sound])
}
}
Подробнее здесь: https://stackoverflow.com/questions/796 ... andby-mode
Мобильная версия