Created
January 9, 2019 11:26
-
-
Save wotjd/fc0fb1fbd3bc482d94c35b9318253856 to your computer and use it in GitHub Desktop.
request local notification with specified scheduled time (date / interval)
This file contains 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
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