通知不会触发

时间:2017-10-18 10:59:15

标签: ios swift notifications unusernotificationcenter

我正在尝试每隔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   小时:13分钟:36小时飞跃:假   小时:13分钟:37 isLeapMonth:false   小时:13分钟:38 isLeapMonth:false   小时:13分钟:39 isLeapMonth:false   可选的(       小时:13       分钟:35,重复:是>)   可选的(       小时:13       分钟:36,重复:是>)   可选的(       小时:13       分钟:37,重复:是>)   可选的(       小时:13       分钟:38,重复:是>)   可选的(       小时:13       分钟:39,重复:是>)

1 个答案:

答案 0 :(得分:0)

根据您在background state中运行该应用的信息,您可以在一段时间后从操作系统中将您的应用设为suspended

<强>背景

  

应用程序在后台并执行代码。大多数应用都会输入此   简要说明他们被暂停的方式。但是,一个应用程序   请求额外执行时间可能会在此状态下保持一段时间   时间。此外,应用程序直接启动到后台   进入此状态而不是非活动状态。有关的信息   如何在后台执行代码,请参阅后台执行。

<强>暂停

  

该应用程序位于后台,但未执行代码。系统   将应用程序自动移动到此状态,并且之前不会通知它们   这样做。暂停时,应用程序仍保留在内存中但不会   执行任何代码。当发生低内存条件时,系统可能会   清除暂停的应用程序,恕不另行通知,以腾出更多空间   前台应用。

我还要说,操作系统suspends也是你的应用程序,即使你运行了一些代码。如果您使用locations (geofencing)voip功能

,则会有一些例外情况

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

相关问题