4

I'm trying to allow the user to schedule notifications to open the app at a certain time every day. So far, I've been able to schedule the first notification by calculating the time between now and when the user selects, and scheduling a notification in X seconds. However, is there a way that I can then set that notification to repeat every day? Here's part of my code in case you're confused:

let newTime: Double = Double(totalDifference)
let notifTrigger = UNTimeIntervalNotificationTrigger(timeInterval: newTime, repeats: false)
let request = UNNotificationRequest(identifier: "openApp", content: notif, trigger: notifTrigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: { error in
    if error != nil {
        print(error!)
        completion(false)
    } else {
        completion(true)
    }
})

Any help is much appreciated

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Spencer Milanak
  • 123
  • 2
  • 10

2 Answers2

9

In your case, change this line:

let notifTrigger = UNTimeIntervalNotificationTrigger(timeInterval: newTime, repeats: false)

to

let notifTrigger = UNTimeIntervalNotificationTrigger(timeInterval: newTime, repeats: true)

From the Documentation:

UNCalendarNotificationTrigger:

Triggers a notification at the specified date and time. You use a UNCalendarNotificationTrigger object to specify the temporal information for the trigger condition of a notification. Calendar triggers can fire once or they can fire multiple times.

NSDateComponents* date = [[NSDateComponents alloc] init];
date.hour = 8;
date.minute = 30; 
UNCalendarNotificationTrigger* trigger = [UNCalendarNotificationTrigger
                     triggerWithDateMatchingComponents:date repeats:YES];

Swift:

var date = DateComponents()
date.hour = 8
date.minute = 30 
let trigger = UNCalendarNotificationTrigger(dateMatching: date, repeats: true)
Community
  • 1
  • 1
Teja Nandamuri
  • 11,045
  • 6
  • 57
  • 109
1

FOR SWIFT3

    let calendar = Calendar(identifier: .gregorian)
    let components = calendar.dateComponents(in: .current, from: date)
    let newComponents = DateComponents(calendar: calendar, timeZone: .current, month: components.month, day: components.day, hour: components.hour, minute: components.minute)
    let trigger = UNCalendarNotificationTrigger(dateMatching: newComponents, repeats: true)
Tushar Sharma
  • 2,839
  • 1
  • 16
  • 38