昨天用好大部分東西了,今天來增加推播吧。
首先要import推播。
import UserNotifications
然後就是開始設定推播裡的內容。
func createNotificationId(selectRow: Int) {
let realm = try! Realm()
let cells = realm.objects(AlarmRealm.self)
if cells.count > 0 {
self.notificationID = cells[selectRow].ID
}
}
func createNotification(selectRow: Int, repeatDay: Int, weekDay: Bool = false) {
let realm = try! Realm()
let cells = realm.objects(AlarmRealm.self)
let content = UNMutableNotificationContent()
content.title = "Clcok"
content.body = cells[selectRow].labelText
content.badge = 0
content.sound = UNNotificationSound.default
let date = Date()
let components: Set<Calendar.Component> = weekDay ? ([.weekday, .hour, .minute]) : ([.hour, .minute])
var dataComponets = Calendar.current.dateComponents(components, from: date)
if weekDay {
dataComponets.weekday = repeatDay
dataComponets.hour = cells[selectRow].Hour
dataComponets.minute = cells[selectRow].Minute
} else {
dataComponets.hour = cells[selectRow].Hour
dataComponets.minute = cells[selectRow].Minute
}
let trigger = UNCalendarNotificationTrigger(dateMatching: dataComponets, repeats: true)
let request = UNNotificationRequest(identifier: cells[selectRow].ID, content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request) { (error) in
if (error != nil) {
print("錯誤!")
}
}
}
那麼今天就到這裡,明天來完善整個鬧鐘APP。