How to repeat local notifications every day at different times

前端 未结 4 571
名媛妹妹
名媛妹妹 2020-12-28 09:45

I\'m working on a prayers application that enables users to set an alarm(local notification) for prayer times, i.e. the user sets the application to notify him for Fajr pray

4条回答
  •  臣服心动
    2020-12-28 10:27

    The best way I found, so far, is to schedule the prayers for the next coming 12 days (12 days * 5 notifications = 60 notifications).

    Note that iOS doesn't allow to schedule more than 64 notifications per app.

    Once the user open the app, I remove all remaining notifications and re-schedule a new ones for the next 12 days.

    The important thing the do, is to add a Background Fetch (job) to your application. In AppDelegate class add this code:

    func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        // Should schedule new notifications from background
        PrayerTimeHelper().scheduleNotifications()
        completionHandler(.newData)
    }
    

    Modify didFinishLaunchingWithOptions method like this:

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // Setup Fetch Interval
    //UIApplication.shared.setMinimumBackgroundFetchInterval(UIApplication.backgroundFetchIntervalMinimum)
        UIApplication.shared.setMinimumBackgroundFetchInterval(12 * 3600) // launch each 12 hours
    }
    

    Here is the methods that schedule the 12 days notifications:

    /// Schedule notifications for the next coming 12 days.
    /// This method is also called by Background Fetch Job
    func scheduleNotifications() {
        DispatchQueue.global(qos: .background).async {
    
            DispatchQueue.main.async {
                self.removeAllPendingAndDeliveredNotifications()
    
                // create notifications for the next coming 12 days
                for index in 0..<12 {
                    let newDate = Calendar.current.date(byAdding: .day, value: index, to: Date())!
                    let prayers = self.getPrayerDatetime(forDate: newDate)
    
                    // create notification for each prayer
                    for iterator in 0..

    This is working fine for my Prayer Times app.

    I hope this will help ;)

提交回复
热议问题