Before issuing a notification, you need to confirm whether you allow the notification.
python
//Get notification permission
UNUserNotificationCenter.current().requestAuthorization(
     options: [.alert, .sound, .badge]){
     (granted, _) in
     if granted{
          UNUserNotificationCenter.current().delegate = self
     }
}
○ If you want to execute it after a second, you need to create a notification with ʻUNTimeIntervalNotificationTrigger (timeInterval :, repeats :)`.
python
let content = UNMutableNotificationContent()
content.sound = UNNotificationSound.default
content.title = "title"
content.subtitle = "subtitle"
content.body = "Contents"
//Execute after specified time
let timer = 10
//Create a notification request
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: TimeInterval(timer), repeats: false)
let identifier = NSUUID().uuidString
let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)
//Register notification request
UNUserNotificationCenter.current().add(request){ (error : Error?) in
     if let error = error {
          print(error.localizedDescription)
     }
}
If you want it to run at the specified time, you need to use ʻUNCalendarNotificationTrigger (dateMatching :, repeats :) `to create a notification.
python
let content = UNMutableNotificationContent()
content.sound = UNNotificationSound.default
content.title = "title"
content.subtitle = "subtitle"
content.body = "Contents"
                
//Specify notification time
let date = Date()
let newDate = Date(timeInterval: 60, since: date)
let component = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute], from: newDate)
                
//Make a request
let trigger = UNCalendarNotificationTrigger(dateMatching: component, repeats: false)
let identifier = NSUUID().uuidString
let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)
                
//Register notification request
UNUserNotificationCenter.current().add(request){ (error : Error?) in
     if let error = error {
          print(error.localizedDescription)
     }
}
        Recommended Posts