在 Day15 中,我們完成了主畫面的 UI 與基本功能。
今天要繼續處理 鬧鐘資料的存取 與 本地通知整合。
func requestNotificationPermission() {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
if granted {
print("Notification permission granted")
} else {
print("Notification permission denied")
}
}
}
@objc func showAlarmAlert(_ notification: Notification) {
guard let noti = notification.object as? UNNotification else { return }
let content = noti.request.content
let alert = UIAlertController(title: content.title, message: content.body, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "確定", style: .default))
present(alert, animated: true)
}
func deleteAlarm(_ alarm: AlarmData, at indexPath: IndexPath) {
let realm = try! Realm()
UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: [alarm.creatTime])
for index in 0..<7 {
UNUserNotificationCenter.current().removePendingNotificationRequests(
withIdentifiers: ["\(alarm.creatTime)_\(index)"]
)
}
try! realm.write { realm.delete(alarm) }
alarms.remove(at: indexPath.row)
tbvData.deleteRows(at: [indexPath], with: .fade)
}
@objc func alarmSwitchChange(_ sender: UISwitch) {
let row = sender.tag
let alarm = alarms[row]
let realm = try! Realm()
try! realm.write { alarm.isEnabled = sender.isOn }
}
func loadAlarms() {
let realm = try! Realm()
let results = realm.objects(AlarmData.self)
alarms = Array(results)
}
今天我們完成了 MainViewController 的資料與通知整合:
到這裡,主畫面功能已經具備 新增、刪除、編輯、提醒,是一個完整的鬧鐘核心。