Skip to content

Instantly share code, notes, and snippets.

@wotjd
Created January 9, 2019 11:26
Show Gist options
  • Save wotjd/fc0fb1fbd3bc482d94c35b9318253856 to your computer and use it in GitHub Desktop.
Save wotjd/fc0fb1fbd3bc482d94c35b9318253856 to your computer and use it in GitHub Desktop.
request local notification with specified scheduled time (date / interval)
import UserNotification
struct LocalNotification {
static func isDuplicatedNotification(identifier: String, completion: @escaping (Bool) -> () = {_ in}) {
UNUserNotificationCenter.current().getPendingNotificationRequests { notifications in
let dumNotis = notifications.filter { $0.identifier == identifier }
completion(!dumNotis.isEmpty)
}
}
// FIXME : notification content currently unchangeable
static func addNotification(identifier: String, scheduleTime: Date = Date(), interval: Double) {
self.isDuplicatedNotification(identifier: identifier) { isDuplicated in
if !isDuplicated {
if let notiTime = Optional(scheduleTime.addingTimeInterval(interval)), notiTime.isFuture() {
let content = UNMutableNotificationContent()
content.title = "alarm"
content.body = "Tick! \(interval) seconds"
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: notiTime.timeIntervalSinceNow, repeats: false)
let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request)
} else {
print("notification time is past")
}
} else {
print("duplicated noti, ignoring..")
}
}
}
static func addScheduleNotifications(identifier: String, scheduleTime: Date = Date(), intervals: [Double]) {
for interval in intervals {
self.addNotification(identifier: "\(identifier)_\(interval)", scheduleTime: scheduleTime, interval: interval)
}
}
}
// usage
LocalNotification.addScheduleNotifications(identifier: "identifier", scheduleItem: Date(), intervals: [5, 10])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment