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

时间:2017-10-08 14:31:47

标签: ios swift uipickerview usernotifications

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

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

1 个答案:

答案 0 :(得分:0)

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

首先,在app delegate中授权通知,如下所示:

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