首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

iOS 鬧鐘 App 開發入門:UserNotifications 框架實作本地通知

     編輯:程式設計綜合問答

核心框架

iOS 10+ 使用 UserNotifications (UN) 框架,替代舊 UILocalNotification。

實作步驟

  1. 請求授權:
    
    UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
        if (granted) { print("授權成功") }
    }
    
  2. 建立通知內容:
    
    let content = UNMutableNotificationContent()
    content.title = "鬧鐘"
    content.body = "起床囉!"
    content.sound = .default
    content.badge = 1
    
  3. 設定觸發條件(日期/時間/週期):
    
    var date = DateComponents()
    date.hour = 7
    date.minute = 30
    let trigger = UNCalendarNotificationTrigger(dateMatching: date, repeats: true)
    
  4. 建立請求並排程:
    
    let request = UNNotificationRequest(identifier: "alarm_0730", content: content, trigger: trigger)
    UNUserNotificationCenter.current().add(request) { error in ... }
    
  5. 前景顯示:實作 UNUserNotificationCenterDelegate,willPresent 回傳 [.alert, .sound]。

進階功能

  • 自訂音效:將 .caf/.wav/.mp3 放入 Bundle,content.sound = UNNotificationSound(named: "custom.caf")。
  • 動作按鈕:UNNotificationAction + UNNotificationCategory,支援「稍後提醒」、「關閉」等互動。
  • 豐富內容:UNNotificationServiceExtension 修改推播內容、下載圖片。

學習資源

新浪部落格完整教學:iOS 鬧鐘程式實作

原答案核心

提供上述部落格連結。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved