A.s.ALI
A.s.ALI

Reputation: 2082

Schedule future UNUserNotificationCenter with condition and limits (iOS)

I know this has been asked several times but there is no concrete solution I have found over the SO.I am working on iOS app and I am using userNotification and all things are working fine but then I have to use the recurring/repeat notifications so here are the conditions that I have to fulfill and wondering how

Case: Show notification to user to check for specific task if it is completed.

  1. show notification everyday until specified date is arrived
  2. Show notification every monday until specified date is arrived
  3. Show notification monthly every specified day until specifed date is arrived

Problem:

  1. I do not know how to schedule repeat notification for given conditions
  2. Is there any limit of notification per app? suppose I have 100 of task and each task may have any of the notification bounded with the uppar given conditions.

Please tell me what could be done? and how I can fulfill my requirements.

Upvotes: 2

Views: 1561

Answers (3)

Pooja Gupta
Pooja Gupta

Reputation: 333

Notification schedule for custom date with body

func schedulingNotificationForCustomDate(body: String, currentDate: Date) {
        // Configure User Notification Center
        let center = UNUserNotificationCenter.current()
        let content = UNMutableNotificationContent()
        content.title = ""
        content.subtitle = ""
        content.body = body
        content.categoryIdentifier = "WeekDay notification"
        content.userInfo = ["NotificationID": "WeekDay notification", "repeat": true, "reschedule": false]
        content.sound = UNNotificationSound.default
        let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: currentDate.timeIntervalSince1970, repeats: true)
        let request = UNNotificationRequest(identifier: "WeekDay notification", content: content, trigger: trigger)
        center.add(request, withCompletionHandler: nil)
    }

Create date as per requirement

extension Date {
    static func createDate(weekday: Int, hour: Int, minute: Int, year: Int) -> Date {
        let calendar = Calendar.current
        var components = DateComponents()
        components.hour = hour
        components.minute = minute
        components.year = year
        components.month = calendar.component(.month, from: Date())
        components.day = calendar.component(.day, from: Date())
        components.weekday = weekday // sunday = 1 ... saturday = 7
        components.timeZone = .current
        return calendar.date(from: components)!
       }
    }

Get the next date for scheduling repeat notification

extension Date {
    static func nextNthDateFromCurrentDate(FromDate: Date, numberOfDays: Int) -> Date {
        return Calendar.current.date(byAdding: .day, value: numberOfDays, to: FromDate)! // where numberOfDays is the number of days for the next date
    }
}

For scheduling notification call

self.schedulingNotificationForCustomDate(body: body, currentDate: Date.nextNthDateFromCurrentDate(FromDate: Date.createDate(weekday: 2, hour: 11, minute: 00, year: year), numberOfDays: 14))

Upvotes: 2

Vadim Nikolaev
Vadim Nikolaev

Reputation: 2132

show notification everyday until specified date is arrived

This is to display a message at a specific time every day

    var dateComponents = DateComponents()
    dateComponents.hour = 10
    dateComponents.minute = 30
    let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)

    if trigger.nextTriggerDate() >= your_specified_date {
        return
    }

Is there any limit of notification per app? suppose I have 100 of task and each task may have any of the notification bounded with the uppar given conditions.

Yes, there are limits. The system keeps the soonest-firing 64 notifications (with automatically rescheduled notifications counting as a single notification) and discards the rest.

Upvotes: 3

DrewG23
DrewG23

Reputation: 437

There is no end date specification on repeating local notifications, so unfortunately you will need to build something custom. However this is a limit of 64 notifications you may queue up according to Apple.

An app can have only a limited number of scheduled notifications; the system keeps the soonest-firing 64 notifications (with automatically rescheduled notifications counting as a single notification) and discards the rest.

I would have an extension that can grab the dates between two dates like so:

extension Date {
    static func dates(from fromDate: Date, to toDate: Date) -> [Date] {
        var dates: [Date] = []
        var date = fromDate

        while date <= toDate {
            dates.append(date)
            guard let newDate = Calendar.current.date(byAdding: .day, value: 1, to: date) else { break }
            date = newDate
        }
        return dates
    }
}

Then you can grab the dates that you need and iterate through each one to create a notification:

let threeDaysFromNowExample = Calendar.current.date(byAdding: .day, value: 3, to: Date())!
let dates = Date.dates(from: Date(), to: threeDaysFromNowExample)

for date in dates {
    let notification = UILocalNotification()
    notification.fireDate = date
    notification.alertBody = "Your alert here!"
    notification.soundName = UILocalNotificationDefaultSoundName
    UIApplication.shared.scheduleLocalNotification(notification)
}

Did not test this code, but should get you started. You may need to massage the extension some to add the ability to grab only Mondays for example.

Upvotes: 1

Related Questions