iT邦幫忙

2025 iThome 鐵人賽

DAY 16
0
Mobile Development

我將成為Swift之強者系列 第 16

Day16 - 仿刻 iOS 鬧鐘實作:資料操作與通知整合

  • 分享至 

  • xImage
  •  

Day16 - 仿刻 iOS 鬧鐘實作:資料操作與通知整合

在 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)
}
  • 從 Realm 載入所有鬧鐘資料。

TableView 功能補充

  • cellForRowAt:顯示鬧鐘時間、標籤、重複設定。
  • didSelectRowAt:點擊進入編輯頁面。
  • trailingSwipeActionsConfigurationForRowAt:左滑刪除功能。

小結

今天我們完成了 MainViewController 的資料與通知整合

  1. 讀取與刪除鬧鐘資料(Realm)。
  2. 與通知系統整合,支援提醒顯示。
  3. 鬧鐘開關狀態切換。

到這裡,主畫面功能已經具備 新增、刪除、編輯、提醒,是一個完整的鬧鐘核心。


上一篇
Day15 - 仿刻 iOS 鬧鐘實作:主畫面 UI 與基本功能
下一篇
Day17 - 仿刻 iOS 鬧鐘實作:MainTableViewCell 介紹
系列文
我將成為Swift之強者18
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言