Skip to content

Instantly share code, notes, and snippets.

@simme
Created November 17, 2016 09:43
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save simme/96264d5ceee394083d18e2c64f42a3a9 to your computer and use it in GitHub Desktop.
Save simme/96264d5ceee394083d18e2c64f42a3a9 to your computer and use it in GitHub Desktop.
Exntension to `UNNotification` for "snoozing" a notification.
//
// UNNotification+Reschedule.swift
// Meal Plan
//
// Created by Simon Ljungberg on 17/11/16.
// License: MIT
//
import UIKit
import UserNotifications
extension UNNotification {
func snoozeNotification(for hours: Int, minutes: Int) {
let content = self.request.content
let identifier = self.request.identifier
guard let oldTrigger = self.request.trigger as? UNCalendarNotificationTrigger else {
fatalError("Cannot reschedule notification without calendar trigger.")
}
var components = oldTrigger.dateComponents
components.hour = (components.hour ?? 0) + hours
components.minute = (components.minute ?? 0) + minutes
let trigger = UNCalendarNotificationTrigger(dateMatching: components, repeats: false)
let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request) { error in
if let error = error {
print("Reschduling failed", error.localizedDescription)
}
}
}
}
@simme
Copy link
Author

simme commented Nov 17, 2016

Won't wrap past midnight and stuff I guess?

@ushpizin
Copy link

I don't think so, DateComponent can handle it. Thanks for sharing the extension!

@real19
Copy link

real19 commented Dec 23, 2017

Thanks!

@MehdiChennoufi
Copy link

Perfect ! Thanks a lot

@cliftonlabrum
Copy link

Super helpful, thank you! : )

@ErAshu
Copy link

ErAshu commented Jul 26, 2022

Hey, Any Body Tell me how to fire repeated notification from a specific date? I have Posted a Stack Over Flow Question. https://stackoverflow.com/questions/73090723/fire-notification-daily-but-after-a-certain-date

What i have achieve yet
✅ Got Specific date notification
✅ Got Daily Notification
❌ Doesn't get Combined

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment