Skip to content

Instantly share code, notes, and snippets.

@cemolcay
Created May 26, 2024 14:43
Show Gist options
  • Save cemolcay/98b73a5c15dcead59917d67041a5a4e3 to your computer and use it in GitHub Desktop.
Save cemolcay/98b73a5c15dcead59917d67041a5a4e3 to your computer and use it in GitHub Desktop.
swift local notification
let center = UNUserNotificationCenter.current()
center.delegate = self
center.requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
if granted {
print("Permission granted")
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().addingTimeInterval(20) // 20 seconds later from now.
let dateComponents = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second], from: testDate)
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: false)
// Create request
let uniqueID = UUID().uuidString // Keep a record of this if necessary
let request = UNNotificationRequest(identifier: uniqueID, content: content, trigger: trigger)
DispatchQueue.main.async {
center.add(request) // Add the notification request
}
} else {
print("Permission denied\n")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment