应用关闭时,通知willPresent不会呼叫

时间:2019-03-02 19:10:32

标签: swift notifications uilocalnotification localnotification

我正试图仅在工作日通知用户,并且不想使用for循环进行操作,因此该通知将布尔重复为true。当应用程序打开时,willPresent函数可以工作,但是当应用程序进入后台时,willPresent函数不会被应用程序调用,并且会在周末向用户发送通知,这是我不希望的。

我已经在didFinishLaunchingWithOptions上设置了UNUserNotificationCenter.current().delegate = self

这是我的AppDelegate中的willPresent函数:

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {

        let date = Date()
        var dayOfWeek = date.getWeekDay()
        if dayOfWeek.rawValue == 1 || dayOfWeek.rawValue == 7{
            print("Don't send a notification")
            completionHandler([])
        }else{
            completionHandler([.alert, .sound, .badge])
        }
    }

我正在使用的扩展名:

extension Date {

    enum WeekDay: Int {
        case sunday = 1
        case monday
        case tuesday
        case wednesday
        case thursday
        case friday
        case saturday
    }

    func getWeekDay() -> WeekDay {
        let calendar = Calendar.current
        let weekDay = calendar.component(Calendar.Component.weekday, from: self)
        return WeekDay(rawValue: weekDay)!
    }
}

任何帮助将不胜感激。谢谢

1 个答案:

答案 0 :(得分:0)

那是因为您应该使用 didReceive 方法来接收后台通知