user24192912
user24192912

Reputation: 1

How to schedule local notifications for specific days and time interval in Swift?

I need to update this schedule function:

func scheduleNotifications(numberOfNotifications: Int) {
    // Create notification content
    let content = UNMutableNotificationContent()
    content.title = "Your Notification Title"
    content.body = "Your Notification Body"
    content.sound = .default
    //content.userInfo = ["url": "myApp://favorite"]
    
    // Define the time range for notifications
    let startDate = DateComponents(hour: 21, minute: 40) // Start time
    let endDate = DateComponents(hour: 22, minute: 40) // End time
    
    // Calculate interval between notifications
    let totalMinutes = (endDate.hour! - startDate.hour!) * 60 + (endDate.minute! - startDate.minute!)
    guard totalMinutes > 0 else {
        print("End time must be after start time")
        return
    }
    
    let interval = max(totalMinutes / numberOfNotifications, 1) // Ensure interval is at least 1 minute
    
    // Define the days of the week for notifications
    let daysOfWeek: [Int] = [1, 3] // Sunday, Tuesday
    
    // Create date components for start and end times
    var date = Date()
    let calendar = Calendar.current
    let currentDateComponents = calendar.dateComponents([.year, .month, .day], from: date)
    var startDateComponents = startDate
    var endDateComponents = endDate
    startDateComponents.year = currentDateComponents.year
    startDateComponents.month = currentDateComponents.month
    startDateComponents.day = currentDateComponents.day
    endDateComponents.year = currentDateComponents.year
    endDateComponents.month = currentDateComponents.month
    endDateComponents.day = currentDateComponents.day
    
    // Create notification triggers for each day of the week within the specified time range
    for day in daysOfWeek {
        date = calendar.date(from: currentDateComponents)!
        let weekday = calendar.component(.weekday, from: date)
        let daysToAdd = (day + 7 - weekday) % 7
        date = calendar.date(byAdding: .day, value: daysToAdd, to: date)!
        
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "EEEE"
        let dayOfWeek = dateFormatter.string(from: date)
        print("Scheduling notification for \(dayOfWeek)")
        
        let triggerDate = calendar.date(bySettingHour: startDate.hour!, minute: startDate.minute!, second: 0, of: date)!
        let endDate = calendar.date(bySettingHour: endDate.hour!, minute: endDate.minute!, second: 0, of: date)!
        
        if triggerDate <= endDate {
            // Schedule notifications at regular intervals
            for i in 0..<numberOfNotifications {
                let triggerTimeInterval = TimeInterval(i * interval * 60)
                if triggerTimeInterval > 0 {
                    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: triggerTimeInterval, repeats: false)
                    let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
                    UNUserNotificationCenter.current().add(request)
                }
            }
        }
    }
}

I tried to add the daysOfWeek array to the trigger variable, but I did not receive notifications as I expected.

My goal is this with this function: I want to send multiple notifications between the start and end time I specify for the days I specify. (e.g., Send 20 notifications between 14:00 and 17:00 on Wednesdays and Saturdays.) Also I need to overcome the limitation of scheduling only 64 notifications at a time in iOS because I need to allow the user to schedule a maximum of 140 notifications per week. How can I handle this?

Upvotes: 0

Views: 90

Answers (1)

Rob Napier
Rob Napier

Reputation: 299265

Also I need to overcome the limitation of scheduling only 64 notifications at a time in iOS because I need to allow the user to schedule a maximum of 140 notifications per week.

That is not possible. Even 64 notifications are not promised.

What you will do instead is to schedule the next several notifications, and when the user launches your app again, you will schedule more. See Prayer Times Notifications in Swift for more discussion on additional tools you can use. For example, push notifications, significant location changes (if appropriate), and background app refresh.

As long at the user regularly interacts with your app, it shouldn't be too difficult, though 20 notifications in 3 hours may be excessive, and you may need to redesign to avoid this use case.

If the user rarely interacts with your app, there is no way to make any of this work. The user needs to demonstrate an interest in your app by periodically launching it or the system will, by design, prevent your app from notifying the user. This is something your design must deal with. If your app is so low-touch that they user isn't expected to launch it very often, you may consider moving your functionality to a widget instead.

Upvotes: 0

Related Questions