在 UIPickerView 上设置日期时的本地通知?

Local Notification when date is set on a UIPickerView?

我想在用户在 UIPicker 上设置日期时设置本地通知。

目前我没有代码,因为我不确定从哪里开始。

我假设您希望用户选择何时发送通知,所以:

首先,在应用委托中授权通知,如下所示:

import UserNotifications

class AppDelegate {
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        let center = UNUserNotificationCenter.current()
        center.requestAuthorization(options: [.alert, .sound, .badge]) { (granted, error) in
            // Enable or disable features based on authorization
        }
        return true
    }
}

接下来,假设您已经创建了一个 datePicker 并将其连接到代码:

@IBOutlet var datePicker: UIDatePicker!

您安排通知的功能是:

func scheduleNotification() {
    let content = UNMutableNotificationContent() //The notification's content
    content.title = "Hi there"
    content.sound = UNNotificationSound.default()

    let dateComponent = datePicker.calendar.dateComponents([.day, .hour, .minute], from: datePicker.date)
    let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponent, repeats: false)

    let notificationReq = UNNotificationRequest(identifier: "identifier", content: content, trigger: trigger)

    UNUserNotificationCenter.current().add(notificationReq, withCompletionHandler: nil)
}

您可以在此处阅读有关 UserNotifications 和通知触发器的更多信息:https://developer.apple.com/documentation/usernotifications