本地推送不需要伺服器,就能讓 App 在指定期間或指定時間向使用者發出提醒,很適合用於待辦提醒、每日通知等情境。整個流程可以拆成「建立並排程」與「接收處理」兩大部分。
先建立一個 UILocalNotification 物件,設定聲音與提示內容,再交給應用程式排程即可:
NSString *str = @"本地推送的訊息";
UIApplication *app = [UIApplication sharedApplication];
UILocalNotification *notification = [[UILocalNotification alloc] init];
notification.soundName = UILocalNotificationDefaultSoundName; // 設定提示音
notification.alertBody = str; // 設定通知內容
// 排程本地推送(關鍵步驟)
[app scheduleLocalNotification:notification];
[notification release];
只要呼叫 scheduleLocalNotification:,系統就會在約定的時間點把通知推給使用者。若需要更精準的控制,還可以設定 fireDate(觸發時間)與 timeZone,甚至用 repeatInterval 做週期性提醒。
當通知被觸發、且 App 正在前景執行時,可以透過 AppDelegate 的下列方法攔截並自行處理:
- (void)application:(UIApplication *)application
didReceiveLocalNotification:(UILocalNotification *)notification {
// 在這裡處理收到的通知內容
}
小提醒:這些 API 屬於較早期的寫法(搭配手動記憶體管理)。在新版 iOS 上,本機通知已改由 UNUserNotificationCenter 統一管理,使用前必須先向使用者請求通知權限。若你在維護舊專案,上面的寫法仍然可讀;若是全新開發,建議直接採用 UserNotifications 框架。