How to set up daily local notification for tasks but don't show it when user completes the task before

前端 未结 1 1237
执笔经年
执笔经年 2021-01-24 05:26

I know similar questions appeared before but I think I need more clarification since i still don\'t know how to make it done. I\'m a beginner programmer so please forgive me any

1条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-24 06:09

    I ended up using multiple notifications for each weekday but set it up in little different way:

    First set up daily reminder using weekday Int as identifier

    func setWeekdayReminder(weekday: Int) {
            let center = UNUserNotificationCenter.current()
            let content = UNMutableNotificationContent()
            content.title = "Daily reminder"
            content.body = "You still have some tasks to complete today."
            content.sound = UNNotificationSound.default
            var dateComponents = DateComponents()
            dateComponents.hour = 18
            dateComponents.minute = 35
            dateComponents.weekday = weekday
            let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true
            let request = UNNotificationRequest(identifier: String(weekday), content: content, trigger: trigger)
    
            center.add(request) { (error) in
                if let error = error {
                    print("Notification Error: ", error)
                }
            }
        }
    

    then i made a function to check if there is any missing day after users launches app (except today, so i won't request todays notification again even after removing it earlier when user completes the task)

    func checkDailyReminder() {
    
           let currentWeekday = Calendar.current.component(.weekday, from: Date())
    
           center.getPendingNotificationRequests { (requests) in
                var weekdayArray : [Int] = []
    
                for each in requests {
                   weekdayArray.append(Int(each.identifier)!)
                }
                for number in 1...7 {
                    if weekdayArray.contains(number) {
                        print("weekdayArray contains weekday \(number)")
                    } else {
                        print("weekdayArray doesnt contain weekday \(number)")
                        if number != currentWeekday {
                              self.setWeekdayReminder(weekday: number)
                        }
                    }
                }
    
            }
        }
    

    Of course it's kind of a hack and when user completes the task and somehow won't go back for a week and open it again on the same weekday then he won't get notification that day but it works for rest of the time.

    0 讨论(0)
提交回复
热议问题