iosswiftusernotifications

Repeat Notifications monthly on specific day


I want to repeat notifications monthly on a specific day, but my concern is, what if the user chooses the 31? Then the Notification would only fire every 2 months and never in February? Because the day component would not match.

Is it possible to set the day to the last day of the month, so when for example February is the next month and the user selected the 31. then it would fire on the last day of February?

I could go the non repeating way and add the notifications manually, but then i would have to face the 64 scheduled notification limit.

Thanks for your help in advance.


Solution

  • The Calendar module is the way to go. Handling dates manually can get very tricky.

    import Calendar
    
    let selectedDate = "31/01/2020"
    
    // Convert string to Date
    let dateF = DateFormatter()
    dateF.dateFormat = "dd/MM/yyyy"
    let myDate = dateF.date(from: selectedDate)!
    
    // Advancing date by a month, to get end of next month.
    Calendar.current.date(byAdding: .month, value: 1, to: myDate)  // "Feb 29, 2020 at 12:00 AM"
    

    In the example above, you can see how to advance date by a month.

    If the user chooses say the 31 of a month, the calendar automatically calculates the end of the next month accurately, even if it has only 28, 29, 30 or 31 days.