Локальные уведомления молчат, когда устройство находится в режиме ожиданияIOS

Программируем под IOS
Ответить
Anonymous
 Локальные уведомления молчат, когда устройство находится в режиме ожидания

Сообщение Anonymous »

Я пытаюсь внедрить некоторые базовые функции уведомления в приложение, которое я создал как часть курса. Однако я столкнулся с проблемой. Я использую локальное уведомление, запускаемое таймером обратного отсчета, когда оно завершается. Однако, как только устройство вступит в резервное положение, уведомление молчит и появляется только как небольшое уведомление на всегда на дисплее (AOD), без какого-либо звука, вибрации или экрана. 16.4. < /P>
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
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «IOS»