本文整理 iOS 中常見的通知與提示機制,涵蓋遠程推送(APNS)以及程式內的震動與音效播放。
1. 註冊推送:
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert];
2. 伺服器推送(以 Java 為例):透過 PushNotificationPayload 建構 payload,並設定提示內容、圖標上的角標數字與鈴音:
PushNotificationPayload payLoad = PushNotificationPayload.fromJSON(message);
payLoad.addAlert("iphone推送測試 www.baidu.com"); // 消息內容
payLoad.addBadge(count); // 圖標上的紅圈數字
payLoad.addSound("default"); // 鈴音,預設
1. 震動
先加入 AudioToolbox 框架:
#import <AudioToolbox/AudioToolbox.h>
呼叫震動:
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
2. 消息聲音
系統音效可直接用編號播放,例如:
AudioServicesPlaySystemSound(1007);
其中 1007 是系統音效的編號。
若要使用自訂音效,可先取得音效檔案路徑,透過 AudioServicesCreateSystemSoundID 建立 SystemSoundID,再播放,用完後以 AudioServicesDisposeSystemSoundID 釋放:
NSString *path = [[NSBundle mainBundle] pathForResource:@"message" ofType:@"wav"];
SystemSoundID soundID;
NSURL *filePath = [NSURL fileURLWithPath:path isDirectory:NO];
AudioServicesCreateSystemSoundID((__bridge CFURLRef)filePath, &soundID);
AudioServicesPlaySystemSound(soundID);
AudioServicesDisposeSystemSoundID(soundID);