-1

I want to set up a local notification when a user sets a date on a UIPicker.

At the moment I have no code because I am not sure where to start.

Eric Aya
  • 69,473
  • 35
  • 181
  • 253

1 Answers1

0

I assume that you want the user to choose when to send the notification, so:

First, authorise for notifications in the app delegate, like so:

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
    }
}

Next, assuming you've created a datePicker and connected it to the code:

@IBOutlet var datePicker: UIDatePicker!

Your function for scheduling the notification is:

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)
}

You can read more about UserNotifications and Notification Triggers here: https://developer.apple.com/documentation/usernotifications

A. Inbar
  • 80
  • 14