Search code examples
iosswiftxcodeuilocalnotification

How do I send local notifications at a specific time in Swift?


I have been looking all over for an answer on how to send notifications at a specific time of day. I need it to display a local notification to the user's device every weekday at 8:00 A.M. I am aware that this question has been answered before. I found a Stack Overflow question: Local Notifications at a specific time

Unfortunately, it was pretty outdated as most of the code was removed from Swift since iOS 11 was released. I needed a more recent answer. I am kind of new to Swift programming. If someone could help me out and give me a more recent answer, that would be amazing!


Solution

  • This is an example of what I have used for scheduling local notifications using Notification Centre.

    let center = UNUserNotificationCenter.current()
    
    let content = UNMutableNotificationContent()
    content.title = "My title"
    content.body = "Lots of text"
    content.sound = UNNotificationSound.default()
    content.categoryIdentifier = "yourIdentifier"
    content.userInfo = ["example": "information"] // You can retrieve this when displaying notification
    
    // Setup trigger time          
    var calendar = Calendar.current
    calendar.timeZone = TimeZone.current
    let testDate = Date() + 5 // Set this to whatever date you need
    let trigger = UNCalendarNotificationTrigger(dateMatching: testDate, repeats: false)
    
    // Create request               
    let uniqueID = UUID().uuidString // Keep a record of this if necessary
    let request = UNNotificationRequest(identifier: uniqueID, content: content, trigger: trigger)
    center.add(request) // Add the notification request
    

    The Date object (represented by testDate above) can be whatever date you want. It is often convenient to create it from DateComponents.

    You will need to ask permission for local notifications in the App Delegate at startup to allow this to work. Here is an example.

    class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
    
        func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    
            // Ask permission for notifications
            let center = UNUserNotificationCenter.current()
            center.delegate = self
            center.requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
                if granted {
                    print("Permission granted")
                } else {
                    print("Permission denied\n")
                }
            }
        }
    }