ios - 重新安排通知操作通知不起作用 Swift

标签 ios swift date unusernotification

我正在尝试在用户点击等待通知操作时重新安排通知。当 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)scope 范围内,我得到了没有秒的日期组件 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 )date,当然那些秒数没有被考虑在内并且使用的日期已经过去了,因此..没有重新安排。 let newComponents = DateComponents(calendar: calendar, timeZone: .current, month: components.month, day: components.day, hour: components.hour, minute: components.minute, second: components.second) 是包含秒的组件的最终日期。

关于ios - 重新安排通知操作通知不起作用 Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52155717/

相关文章:

ios - Swift - AWS S3 从图片库上传图片并下载

java - 如何使用默认区域解析 ZonedDateTime?

javascript - 如何使用纯js重置日期毫秒

java - Spring,Java : Error, 无法将 java.lang.Long 转换为 java.util.Date

ios - 如何在 objc_weak_error 上设置中断

ios - 模仿 iOS 10 上的 adjustmentContentInset?

ios - 降低约束的优先级到底有什么作用?

ios - 在 Swift 中使用 PageViewController 设置 NSTimer

ios - 在 UIViewController 之间共享 View ?第二个 viewController "steals"从第一个 View 开始?

swift - 如何释放 NSColorPanel?