Comment mettre des notifications sur l'application iOS à répéter toutes les une (1) heure?

J'ai essayé de mettre des notifications dans mon application, il était censé répéter toutes les heures mais il répète non réglementé, pour être clair, il répète parfois 30min parfois une heure parfois pendant longtime etc. Code que j'ai utilisé dans "AppDelegate.swift ":

class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. //Notification Repeat application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound, categories: nil)) return true } 

et le code que j'ai utilisé dans "ViewController.swift":

 //Notification Repeat var Time = 1 override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. //Notification Repeat var Timer = NSTimer.scheduledTimerWithTimeInterval(3600.0, target: self, selector: Selector("activateNotifications"), userInfo: nil, repeats: true) } //Notification Repeat func activateNotifications() { Time -= 1 if (Time <= 0){ var activateNotifications = UILocalNotification() activateNotifications.alertAction = “Hey" activateNotifications.alertBody = “Hello World!" activateNotifications.fireDate = NSDate(timeIntervalSinceNow: 0) UIApplication.sharedApplication().scheduleLocalNotification(activateNotifications) } } 

Quelqu'un peut-il m'aider, où je me suis trompé?

Vous n'avez pas besoin de la timer du tout. La class UILocalNotification a une propriété intitulée repeatInterval qui, comme vous pouvez vous y attendre, définit l'intervalle auquel la notification sera répétée.

En fonction de cela, vous pouvez planifier une notification locale répétée toutes les heures de la façon suivante:

 func viewDidLoad() { super.viewDidLoad() var notification = UILocalNotification() notification.alertBody = "..." // text that will be displayed in the notification notification.fireDate = NSDate() // right now (when notification will be fired) notification.soundName = UILocalNotificationDefaultSoundName // play default sound notification.repeatInterval = NSCalendarUnit.CalendarUnitHour // this line defines the interval at which the notification will be repeated UIApplication.sharedApplication().scheduleLocalNotification(notification) } 

REMARQUE: assurez-vous d'exécuter le code lorsque vous ne lancez la notification qu'une seule fois, car il planifie une notification différente chaque fois qu'elle est exécutée. Pour une meilleure compréhension des notifications locales, vous pouvez lire les notifications locales dans iOS 8 avec Swift (Partie 1) et les notifications locales dans iOS 8 avec Swift (Partie 2) .