【发布时间】:2017-07-22 21:00:35
【问题描述】:
我进行了以下设置,但根本没有发出任何通知。
基于堆栈上的其他类似问题,我为每个请求添加了一个唯一标识符,并且我还将正文添加到内容中。
我有这个请求用户许可的功能。
func sendIntNotifications()
{
//1. Request permission from the user
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound], completionHandler:
{
(granted, error) in
if granted
{
print ("Notification access granted")
}
else
{
print(error?.localizedDescription)
}
UNUserNotificationCenter.current().delegate = self
})
// This function has a lot of other code that then calls this function to set multiple notifications :
for daysInt in outputWeekdays
{
scheduleActualNotification(hourInt: hourInt, minuteInt: minuteInt, dayInt: daysInt)
}
}
这些是主要功能:
func scheduleActualNotification(hourInt hour: Int, minuteInt minute: Int, dayInt day: Int)
{
// 3.1 create date components for each day
var dateComponents = DateComponents()
dateComponents.hour = hour
dateComponents.minute = minute
dateComponents.day = day
//3.2 Create a calendar trigger for that day at that time
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents,
repeats: true)
//3.3 Message content
let content = UNMutableNotificationContent()
content.title = "Test Title"
content.body = "Test body"
content.badge = 1
// 3.4 Create the actual notification
let request = UNNotificationRequest(identifier: "bob \(i+1)",
content: content,
trigger: trigger)
// 3.5 Add our notification to the notification center
UNUserNotificationCenter.current().add(request)
{
(error) in
if let error = error
{
print("Uh oh! We had an error: \(error)")
}
}
}
此功能是在此应用打开时接收通知
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void)
{
completionHandler([.alert, .sound]) //calls the completionHandler indicating that both the alert and the sound is to be presented to the user
}
也没有错误,哈哈!
编辑:
所以从用户界面中,我选择了 2350 和周六和周日。我希望通知会在周六和周日的 2350 发送。
我做了print(daysInt)。它的第一个值为 1,第二个值为 7,这与预期的一样。其次,我进入函数scheduleActualNotification,小时的值为23,分钟的值为50,正如预期的那样。
谢谢!
【问题讨论】:
-
如果您的应用在后台...您还会收到警报吗?如果是,那么您已经正确添加了通知,但没有正确处理它,即如果应用程序处于前台时它不能正常工作,那么很可能是您使用
UNUserNotificationCenter.current().delegate = YOUROBJECT设置为您的委托的对象与编写willPresent函数的对象不同,即您在一个类中“采用”但在另一个类中“符合”。在completionHandler([.alert, .sound])上放置一个断点,看看它是否被调用过。我的猜测是它永远不会被调用。 -
但是现在你还没有显示哪个类你添加了请求,也没有显示你从哪个类处理它。请在您的代码中显示,以便我们更好地帮助您
-
您好,感谢您的回复。根本没有通知 - 无论是在后台还是在前台。所有这些代码都在
ViewController.swift文件中,课程开始如下:import UIKitimport UserNotificationsclass ViewController: UIViewController, UITableViewDataSource,UITableViewDelegate, UNUserNotificationCenterDelegate{ -
所以既然你说你没有得到任何错误,我能想到的唯一问题是你通过的时间不正确。向我们展示您传递给
scheduleActualNotification函数的内容的示例。作为验证您经过的时间的好方法。见this答案 -
您好,我设置了一个断点,并且正确地传递了时间。我还注意到您指出代码永远不会输入
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound], completionHandler:但这很奇怪,因为通知即将到来,要求用户允许发送通知。
标签: ios swift ios10 uilocalnotification