user10166622
user10166622

Reputation:

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!

Upvotes: 6

Views: 11878

Answers (2)

GuimarãesGabrielG
GuimarãesGabrielG

Reputation: 101

Swift 5

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

import UserNotifications

class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
    
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    
    //MARK: Authorization
    let center = UNUserNotificationCenter.current()
    
    
    //Delegate for UNUserNotificationCenterDelegate
    center.delegate = self
    
    //Permission for request alert, soud and badge
    center.requestAuthorization(options: [.alert, .sound, .badge]) { (granted, error) in
        // Enable or disable features based on authorization.
        if(!granted){
            print("not accept authorization")
        }else{
            print("accept authorization")
            
            center.delegate = self
            
            
        }
    }
    return true
}

}

send notification

let content = UNMutableNotificationContent()
        content.title = NSString.localizedUserNotificationString(forKey: "We have a new message for you", arguments: nil)
        content.body = NSString.localizedUserNotificationString(forKey: "Open the app for see", arguments: nil)
        content.sound = UNNotificationSound.default
        content.badge = 1
        let identifier = id.uuidString

    //Receive notification after 5 sec
    //let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
    
    //Receive with date
    var dateInfo = DateComponents()
    dateInfo.day = day //Put your day
    dateInfo.month = month //Put your month
    dateInfo.year = year // Put your year
    dateInfo.hour = 8 //Put your hour
    dateInfo.minute = 0 //Put your minutes
    
    //specify if repeats or no
    let trigger = UNCalendarNotificationTrigger(dateMatching: dateInfo, repeats: true)
    
    let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)
    let center = UNUserNotificationCenter.current()
    print(identifier)
    center.add(request) { (error) in
        if let error = error {
            print("Error \(error.localizedDescription)")
        }else{
            print("send!!")
        }
    }

remembering to read this in the documentation:

https://developer.apple.com/library/archive/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/index.html#//apple_ref/doc/uid/TP40008194-CH3-SW1

Upvotes: 1

Chris
Chris

Reputation: 4411

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

Upvotes: 1

Related Questions