2017-09-07 8 views
1

Dans mon application, je souhaite ajouter des notifications locales. Le scénario sera que l'utilisateur peut sélectionner n'importe quel temps et jours de lundi à dimanche. Par exemple, si l'utilisateur sélectionne Lun, Thur et Sat comme jours et heures à 23h00, l'utilisateur doit maintenant être averti à tous les jours sélectionnés et à cette heure particulière.Définir des notifications locales pour des jours et des heures spécifiques 3

code:

let notification = UNMutableNotificationContent() 
notification.title = "Danger Will Robinson" 
notification.subtitle = "Something This Way Comes" 
notification.body = "I need to tell you something, but first read this." 

let notificationTrigger = UNTimeIntervalNotificationTrigger(timeInterval: 60, repeats: true) 
// let test = UNCalendarNotificationTrigger() 
let request = UNNotificationRequest(identifier: "notification1", content: notification, trigger: notificationTrigger) 
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil) 

J'utilise ce code, mais cela ne fonctionne pas selon ce que je dois.

+0

Votre timeInterval dans ce code est 60seconds. Donc, il se déclenchera après 60 secondes. Vous n'avez implémenté aucune logique de déclenchement sur plusieurs jours? –

+0

Quelque chose comme https://stackoverflow.com/questions/41800189/local-notifications-repeat-interval-in-swift-3 semble intéressant – MadProgrammer

Répondre

4

Pour obtenir des notifications locales qui se répètent sur un certain jour de la semaine à un certain temps, vous pouvez utiliser un UNCalendarNotificationTrigger:

let notification = UNMutableNotificationContent() 
notification.title = "Danger Will Robinson" 
notification.subtitle = "Something This Way Comes" 
notification.body = "I need to tell you something, but first read this." 

// add notification for Mondays at 11:00 a.m. 
var dateComponents = DateComponents() 
dateComponents.weekday = 2 
dateComponents.hour = 11 
dateComponents.minute = 0 
let notificationTrigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true) 

let request = UNNotificationRequest(identifier: "notification1", content: notification, trigger: notificationTrigger) 
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil) 

Si vous souhaitez recevoir les notifications lundi, jeudi et samedi à 11h00, vous devez ajouter 3 demandes distinctes. Pour pouvoir les supprimer, vous devez garder une trace des identifiants.