推播負載 (userInfo) 在 AppDelegate 接收,需傳遞給特定 ViewController 顯示。
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
// 儲存推播資料
[[NSUserDefaults standardUserDefaults] setObject:userInfo forKey:@"RemoteNotificationUserInfo"];
[[NSUserDefaults standardUserDefaults] synchronize];
// 發送通知通知 ViewController (可選)
[[NSNotificationCenter defaultCenter] postNotificationName:@"RemoteNotificationReceived" object:nil userInfo:userInfo];
completionHandler(UIBackgroundFetchResultNewData);
}
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
// 取得資料
NSDictionary *userInfo = [[NSUserDefaults standardUserDefaults] objectForKey:@"RemoteNotificationUserInfo"];
if (userInfo) {
// 更新 UI、導航至詳細頁...
[[NSUserDefaults standardUserDefaults] removeObjectForKey:@"RemoteNotificationUserInfo"]; // 用完清除
}
}
// 或監聽通知即時反應
- (void)viewDidLoad {
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleRemoteNotification:) name:@"RemoteNotificationReceived" object:nil];
}
- (void)handleRemoteNotification:(NSNotification *)notification {
NSDictionary *userInfo = notification.userInfo;
// 立即處理
}
| 方案 | 優點 | 缺點 | 適用場景 |
|---|---|---|---|
| NSUserDefaults | 簡單、跨啟動持久化 | 非即時、需主動讀取 | App 冷啟動由推播進入 |
| NSNotificationCenter | 即時、解耦 | App 未啟動時收不到 | App 前景/背景運行中 |
| 單例/共享模型 | 型別安全、即時 | 需自行管理生命週期 | 複雜資料流 |
| Core Data / Realm | 結構化、查詢強大 | 過重 | 大量歷史記錄 |
didFinishLaunchingWithOptions 中檢查 launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey],直接導航目標頁面。NSNotificationCenter 廣播,目標 VC 監聽處理。UNUserNotificationCenterDelegate 統一處理推播展示與點擊回調。組合使用 NSUserDefaults (冷啟動備份) + NSNotificationCenter (即時傳遞),可完整覆蓋推播資料傳遞需求。