UserNotification in 3 days then repeat every day/hour - iOS 10

前端 未结 2 1698
死守一世寂寞
死守一世寂寞 2020-12-11 04:07

UILocalNotification has been depreciated so I would like to update my code to the UserNotification framework:

let alertDays = 3.0
let alertSeconds = alertDay         


        
2条回答
  •  春和景丽
    2020-12-11 04:42

    This should work:

    func addNotificationForAlarm(alarm: MyAlarm) {
    
        let myAlarmNotifContent = UNMutableNotificationContent()
        myAlarmNotifContent.title = "Reminder"
        myAlarmNotifContent.body = alarm.activity
        myAlarmNotifContent.sound = UNNotificationSound.default()
    
        if alarm.repeatDays.count == 1 {
    
        } else {
    
            for index in 1...alarm.repeatDays.count {
                createNotif(date: alarm.date, weekDay: index, content: myAlarmNotifContent)
            }
        }
    
    }
    
    private func createNotif(date: Date, weekDay: Int, content: UNNotificationContent) {
    
        var dateComponent = DateComponents()
        dateComponent.weekday = weekDay
        dateComponent.hour = Calendar.current.dateComponents([.hour], from: date).hashValue
        dateComponent.minute = Calendar.current.dateComponents([.minute], from: date).hashValue
    
        let myAlarmTrigger = UNCalendarNotificationTrigger(dateMatching: dateComponent, repeats: true)
    
        setupNotificationSettings()
    
        let identifier = "Your-Notification"
        let request = UNNotificationRequest(identifier: identifier, content: content, trigger: myAlarmTrigger)
        let center = UNUserNotificationCenter.current()
        center.add(request, withCompletionHandler: { (error) in
            if error != nil {
                //TODO: Handle the error
            }
        })
    }
    

提交回复
热议问题