-1

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

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

4

1 回答 1

0

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

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

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

于 2017-10-08T16:20:43.493 回答