使用者收到遠端推播後點擊通知進入 App,我們通常希望能直接帶他去看那則訊息,而不是停在首頁。要做到這件事,關鍵在於「判斷這次啟動是不是由通知觸發的」,以及「在uitable的呈現時機上做轉接」。
如果 App 原本沒有在背景執行,使用者點通知後會走 didFinishLaunchingWithOptions:,推播的 userInfo 就藏在 launchOptions 裡:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
NSDictionary *remoteNotification = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
取到的 remoteNotification 不為空,就代表這次啟動來自推播。此時宣告一個標記位,後續邏輯都靠它分流:
@property (nonatomic) BOOL isLaunchedByNotification;
接著系統一定會呼叫:
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
iOS 7 之後建議改用帶 completion handler 的版本,方便向系統回報推播是否已處理:
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
這個方法的優點是呼叫時 MainViewController 通常已經完成初始化,所以我們可以直接在 MainViewController 註冊通知,用來決定要切換哪個畫面。
// 訂閱「直接開啟某個分支畫面」的通知 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(presentView:) name:@"PresentView" object:nil]; // 訂閱「彈出提示框」的通知,適合使用者正在操作 App 時收到訊息 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showNotification:) name:@"Notification" object:nil];
於是 AppDelegate 收到推播時,只要判斷 isLaunchedByNotification,就能決定是走「直接跳畫面」還是「跳提示框」。
有些場景(例如來電、警報)希望提示不會只響一下就停。這裡不是播放音樂檔,而是用 AudioToolbox 搭配完成回呼達到「循環」的效果。先引入標頭:
#import <AudioToolbox/AudioToolbox.h>
註冊一段系統音效(範例直接用預設的 1007):
@property (nonatomic, assign) SystemSoundID soundID; NSString *path = [[NSBundle mainBundle] pathForResource:soundName ofType:nil]; AudioServicesCreateSystemSoundID((__bridge CFURLRef)[NSURL fileURLWithPath:path], &_soundID); AudioServicesAddSystemSoundCompletion(_soundID, NULL, NULL, soundCompleteCallback, NULL);
核心就是反覆播放,並透過回呼接續下一輪:
// 反覆呼叫即可持續
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
AudioServicesPlaySystemSound(_soundID);
// 音效播完後的回呼,重新觸發一次
void soundCompleteCallback(SystemSoundID soundID, void *clientData) {
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
AudioServicesPlaySystemSound(soundID);
}
// 停止播放
-(void)stopAlertSoundWithSoundID:(SystemSoundID)soundID {
AudioServicesDisposeSystemSoundID(kSystemSoundID_Vibrate);
AudioServicesDisposeSystemSoundID(soundID);
AudioServicesRemoveSystemSoundCompletion(soundID);
}
要注意的是,這類持續性提示容易讓使用者反感,正式產品上建議只在明確必要的情境使用,並提供關閉入口。