首页 文章

通知不会触发

提问于
浏览
1

我试图从上午到下午每隔5分钟创建相同的通知 .

UNUserNotificationCenter.current().requestAuthorization(options: [ .alert, .sound, .badge], completionHandler: {didAllow, error in})


    let hours: [Int] = [13]
    for hour in hours {
        for minute in stride(from: 35, to: 40, by: 1){
            let content = UNMutableNotificationContent()
            content.title = "Title"
            content.body = "Notification body"
            var dateComponents = DateComponents()
            dateComponents.hour = hour
            dateComponents.minute = minute
            print(dateComponents)
            let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)
            let request = UNNotificationRequest(identifier: ("\(hour)"+"\(minute)"+"timerDone"), content: content, trigger: trigger)
            let center = UNUserNotificationCenter.current()
            center.add(request, withCompletionHandler: nil)
            center.getPendingNotificationRequests(completionHandler: { requests in
                for request in requests {
                    print(request.trigger)
                }
            })
        }
    }

它不会在计划的时间显示通知,但是

center.getPendingNotificationRequests(completionHandler: { requests in
                for request in requests {
                    print(request.trigger)
                }
            })

在调试中打印有待处理的通知 . 因此,通知被添加到中心并等待时间,但不要触发 .

有任何想法吗?

调试显示的内容:

小时:13分钟:35 isLeapMonth:false hour:13分钟:36 isLeapMonth:false hour:13分钟:37 isLeapMonth:false hour:13分钟:38 isLeapMonth:false hour:13分钟:39 isLeapMonth:false可选(小时: 13分钟:35,重复:是>)可选(小时:13分钟:36,重复:是>)可选(小时:13分钟:37,重复:是>)可选(小时:13分钟:38,重复:是>)可选(小时:13分钟:39,重复:是>)

1 回答

  • 0

    鉴于您的应用程序在 background state 中运行的信息,可能是您的应用程序将在一段时间后从操作系统运行 suspended .

    Background

    该应用程序在后台并执行代码 . 大多数应用程序会暂停进入此状态 . 但是,请求额外执行时间的应用程序可能会在此状态下保留一段时间 . 此外,直接启动到后台的应用程序进入此状态而不是非活动状态 . 有关如何在后台执行代码的信息,请参阅后台执行 .

    Suspended

    该应用程序在后台但未执行代码 . 系统会自动将应用程序移动到此状态,并且在执行此操作之前不会通知它们 . 暂停时,应用程序仍保留在内存中,但不执行任何代码 . 当发生内存不足的情况时,系统可能会清除已暂停的应用程序而不通知为前台应用程序腾出更多空间 .

    我还要说,操作系统也是你的应用程序,即使你运行了一些代码 . 如果您使用 locations (geofencing)voip 功能,则会有一些例外情况

    请查看以下文档:https://developer.apple.com/library/content/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/TheAppLifeCycle/TheAppLifeCycle.html

相关问题