ios - 重新安排通知操作通知不起作用 Swift
问题描述
当用户点击等待通知操作时,我正在尝试重新安排通知。当triggerNotification()
第一次被调用时Date
由日期选择器提供,但是当它被响应调用时,会从时间间隔中获取日期。在我设置 的didReceiveResponse
方法内部并将其传递给参数。延迟的通知永远不会到达。我不明白这是函数调用问题还是因为我看到它的打印是正确的。这是代码:case:waitActionIdentifier:
newDate
triggerNotification
newDate
class ViewController: UIViewController {
@IBAction func datePickerDidSelectNewDate(_ sender: UIDatePicker) {
let selectedDate = sender.date
let delegate = UIApplication.shared.delegate as? AppDelegate
// delegate?.scheduleNotification(at: selectedDate)
delegate?.triggerNotification(at: selectedDate)
}
}
和 AppDelegate
import UIKit
import UserNotifications
@UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
UNUserNotificationCenter.current().delegate = self
configureCategory()
triggerNotification(at: Date())
requestAuth()
return true
}
let category = "Notification.Category.Read"
private let readActionIdentifier = "Read"
private let waitActionIdentifier = "Wait"
private func requestAuth() {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { (success, error) in
if let error = error {
print("Request Authorization Failed (\(error), \(error.localizedDescription))")
}
}
}
func triggerNotification(at date: Date) {
// Create Notification Content
let notificationContent = UNMutableNotificationContent()
//compone a new Date components because components directly from Date don't work
let calendar = Calendar(identifier: .gregorian)
let components = calendar.dateComponents(in: .current, from: date)
let newComponents = DateComponents(calendar: calendar, timeZone: .current, month: components.month, day: components.day, hour: components.hour, minute: components.minute)
//create the trigger with above new date components, with no repetitions
let trigger = UNCalendarNotificationTrigger(dateMatching: newComponents, repeats: false)
// Configure Notification Content
notificationContent.title = "Hello"
notificationContent.body = "Kindly read this message."
// Set Category Identifier
notificationContent.categoryIdentifier = category
// Add Trigger
// let notificationTrigger = UNTimeIntervalNotificationTrigger(timeInterval: 10.0, repeats: false)
// // Create Notification Request
let notificationRequest = UNNotificationRequest(identifier: "test_local_notification", content: notificationContent, trigger: trigger)
//
// Add Request to User Notification Center
UNUserNotificationCenter.current().add(notificationRequest) { (error) in
if let error = error {
print("Unable to Add Notification Request (\(error), \(error.localizedDescription))")
}
}
}
private func configureCategory() {
// Define Actions
let read = UNNotificationAction(identifier: readActionIdentifier, title: "Read", options: [])
let wait = UNNotificationAction(identifier: waitActionIdentifier, title : "Wait", options: [])
// Define Category
let readCategory = UNNotificationCategory(identifier: category, actions: [read, wait], intentIdentifiers: [], options: [])
// Register Category
UNUserNotificationCenter.current().setNotificationCategories([readCategory])
}
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.alert])
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
switch response.actionIdentifier
{
case readActionIdentifier:
print("Read tapped")
case waitActionIdentifier:
let actualDate = Date()
let newDate: Date = Date(timeInterval: 10, since: actualDate)
self.triggerNotification(at: newDate)
print("Wait tapped")
print(actualDate)
print(newDate)
default:
print("Other Action")
}
completionHandler()
}
}
解决方案
在用@VIP-DEV 和@Honey 尝试了不同的事情之后,我终于明白了在点击通知中的等待操作按钮时重新安排通知的问题在哪里。在func triggerNotification(at date: Date)
范围内,我得到了没有秒数的日期组件,let newComponents = DateComponents(calendar: calendar, timeZone: .current, month: components.month, day: components.day, hour: components.hour, minute: components.minute)
所以当函数的新调用是使用let newDate: Date = Date(timeInterval: 5.0 , since: actualDate)
日期进行时,当然这些秒数没有被考虑在内,并且使用的日期已经过去,因此..没有重新安排。
let newComponents = DateComponents(calendar: calendar, timeZone: .current, month: components.month, day: components.day, hour: components.hour, minute: components.minute, second: components.second)
是包含秒数的组件的最终日期。
推荐阅读
- c# - 使用 .NET 字典的 C# 函数缺少导入的 XML 文档
OpenEdge 编辑器中的输入类型 - angular - 我如何等待另一个 http 呼叫?
- google-cloud-platform - 如何检查 GKE 中使用的启动磁盘大小消耗?
- django-rest-framework - Api 在 open edx 的讨论论坛中创建帖子
- triggers - 如何为同一个对象创建两个触发器
- java - 如何将主体对象构建到集成测试中
- python - KNN with scikit-learn:如何使用 NaN 欧几里得度量获得距离矩阵?
- css - 如何在带有标签的 css 中创建缺口边框?
- amazon-web-services - Lambda 中的 AWS create_multipart_upload
- r - 在R中更改数据框中的日期值