Working with Local Notifications and the UserNotifications framework.
Check for authorization status
UNUserNotificationCenter.current().getNotificationSettings { (settings) in
if settings.authorizationStatus == .authorized {
//
} else {
self.requestNotificationPermissions()
}
}Request authorization
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .sound]) { (granted, error) in
if let error = error {
// error encountered
print("error encountered: \(error)")
return
}
if granted {
print("access granted")
} else {
print("access denied")
}
}let content = UNMutableNotificationContent()
content.title = "Code Alert"
content.body = "Starting the day with code"let timeInterval = Date().timeIntervalSinceNow + 5
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: timeInterval, repeats: false)- UNCalendarNofificationTrigger
- UNTimeIntervalNotificationTrigger
- UNLocationNotificationTrigger
let identifier = "sundayAlarm"
let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)center.add(request) { (error) in
if let error = error {
print("request error: \(error)")
}
}func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
configureNoficationCenter()
return true
}extension AppDelegate: UNUserNotificationCenterDelegate {
func configureNoficationCenter() {
UNUserNotificationCenter.current().delegate = self
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
// code here
}
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler(.alert)
}
}let imageURL = Bundle.main.url(forResource: "pursuit-logo", withExtension: "png")!
do {
let attachment = try UNNotificationAttachment(identifier: "sundayAlarm", url: imageURL)
content.attachments = [attachment]
} catch {
print("could not load attached with error: \(error)")
}UNUserNotificationCenter.current().getPendingNotificationRequests { (requests) in
let request = requests.filter { $0.identifier == "sundayAlarm" }
dump(request)
}UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: ["sundayAlarm"])content.sound = UNNotificationSound(named: UNNotificationSoundName(rawValue: "deduction.mp3"))//.default

