Created
May 26, 2024 14:43
-
-
Save cemolcay/98b73a5c15dcead59917d67041a5a4e3 to your computer and use it in GitHub Desktop.
swift local notification
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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