在多數行動應用中,任何時刻通常只有一個 App 處於活躍狀態。當其他應用發生了使用者關心的事情,就必須靠通知機制把訊息送達。iOS 的通知機制包含兩類:本地通知(Local Notification)與推送通知(Remote/Push Notification)。兩者在系統中的呈現方式一致——橫幅或彈出提醒,點擊後可開啟應用——但實作原理完全不同。
更麻煩的是,還有第三個容易混淆的概念:通知中心(Notification Center)。本文依序說明這三者,並釐清它們的關係。
本地通知由應用自身觸發,本質上是一種基於時間的行為,例如鬧鐘、待辦提醒,或「很久沒用了,回來看看」這類喚回提示。建立一個本地通知大致分為五步:
UILocalNotification 物件。fireDate。userInfo(此步可選)。scheduleLocalNotification: 排程,或以 presentLocalNotificationNow: 立即呈現。下面以「版本更新後長期未使用的喚回提醒」為例。這個範例幾乎不涉及介面操作,邏輯全在 AppDelegate 中:啟動時若尚未取得通知授權就先請求授權;不論使用者是否同意,didRegisterUserNotificationSettings: 都會被呼叫,我們在其中判斷結果並決定是否排程通知。
#import "AppDelegate.h"
#import "KCMainViewController.h"
@interface AppDelegate ()
@end
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
_window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
_window.backgroundColor = [UIColor colorWithRed:249/255.0
green:249/255.0
blue:249/255.0
alpha:1];
// 設定全域導航列風格與顏色
[[UINavigationBar appearance] setBarTintColor:[UIColor colorWithRed:23/255.0
green:180/255.0
blue:237/255.0
alpha:1]];
[[UINavigationBar appearance] setBarStyle:UIBarStyleBlack];
KCMainViewController *mainController = [[KCMainViewController alloc] init];
_window.rootViewController = mainController;
[_window makeKeyAndVisible];
// 若已取得通知授權則直接建立本地通知,否則先請求授權
// 注意:若從未請求過授權,系統設定中不會出現對應的通知項目
if ([[UIApplication sharedApplication] currentUserNotificationSettings].types
!= UIUserNotificationTypeNone) {
[self addLocalNotification];
} else {
[[UIApplication sharedApplication] registerUserNotificationSettings:
[UIUserNotificationSettings settingsForTypes:
UIUserNotificationTypeAlert |
UIUserNotificationTypeBadge |
UIUserNotificationTypeSound
categories:nil]];
}
return YES;
}
// 呼叫 registerUserNotificationSettings: 之後執行
- (void)application:(UIApplication *)application
didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings {
if (notificationSettings.types != UIUserNotificationTypeNone) {
[self addLocalNotification];
}
}
// 進入前台時清除應用圖示上的數字
- (void)applicationWillEnterForeground:(UIApplication *)application {
[[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
}
#pragma mark - 私有方法
- (void)addLocalNotification {
UILocalNotification *notification = [[UILocalNotification alloc] init];
// 10 秒後觸發
notification.fireDate = [NSDate dateWithTimeIntervalSinceNow:10.0];
notification.repeatInterval = 2;
// notification.repeatCalendar = [NSCalendar currentCalendar];
// 使用前最好設定時區等資訊,以便自動同步時間
notification.alertBody = @"最近新增了諸多有趣的功能,是否立即體驗?";
notification.applicationIconBadgeNumber = 1;
notification.alertAction = @"開啟應用";
notification.alertLaunchImage = @"Default";
// notification.soundName = UILocalNotificationDefaultSoundName;
notification.soundName = @"msg.caf"; // 自訂聲音需真機才能聽到
// 綁定附加資訊
notification.userInfo = @{@"id": @1, @"user": @"Kenshin Cui"};
[[UIApplication sharedApplication] scheduleLocalNotification:notification];
}
// 不再需要時記得移除
- (void)removeNotification {
[[UIApplication sharedApplication] cancelAllLocalNotifications];
}
@end
幾個必須知道的限制:
cancelLocalNotification: 或 cancelAllLocalNotifications。那麼 userInfo 該如何取回?點擊通知(或在鎖屏介面滑動)時,系統預設會開啟應用,此時有兩種情況:
application:didFinishLaunchingWithOptions:,此時可從 launchOptions 中取出鍵為 UIApplicationLaunchOptionsLocalNotificationKey 的物件,那就是觸發的通知,再讀取它的 userInfo。application:didReceiveLocalNotification:,參數中已有 notification 物件,直接讀 userInfo 即可。- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// ... 建立視窗與 rootViewController ...
[self addLocalNotification];
// 冷啟動時由此取得通知
UILocalNotification *notification =
[launchOptions valueForKey:UIApplicationLaunchOptionsLocalNotificationKey];
NSDictionary *userInfo = notification.userInfo;
NSLog(@"didFinishLaunchingWithOptions: The userInfo is %@.", userInfo);
return YES;
}
// 應用仍在執行時收到本地通知
- (void)application:(UIApplication *)application
didReceiveLocalNotification:(UILocalNotification *)notification {
NSDictionary *userInfo = notification.userInfo;
NSLog(@"didReceiveLocalNotification: The userInfo is %@", userInfo);
}
實測時建議分兩種情境驗證:一是啟動後關閉應用,等收到通知再點擊進入;二是啟動後先進入後台,收到通知後點擊進入。兩者會分別走上面兩條路徑。拿到 userInfo 之後,就可以依參數導航到不同畫面——例如更新通知就跳到更新內容頁。
推送通知由應用服務提供商發起,經由蘋果的 APNs(Apple Push Notification Server)轉發到用戶裝置。整體流程是:

把流程細化後,開發端要做的事如下。
只有註冊過的應用才可能收到訊息,通常以 registerUserNotificationSettings: 搭配 registerForRemoteNotifications 完成(iOS 8 的通知註冊方式有變,iOS 7 及更早版本請參考舊 API)。兩個前提條件必須先備妥:
application:didRegisterForRemoteNotificationsWithDeviceToken: 中取得令牌,此方法在註冊成功後呼叫。application:didFailToRegisterForRemoteNotificationsWithError: 回報詳細錯誤。#import "AppDelegate.h"
#import "KCMainViewController.h"
@interface AppDelegate ()
@end
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
_window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
_window.backgroundColor = [UIColor colorWithRed:249/255.0
green:249/255.0
blue:249/255.0
alpha:1];
[[UINavigationBar appearance] setBarTintColor:[UIColor colorWithRed:23/255.0
green:180/255.0
blue:237/255.0
alpha:1]];
[[UINavigationBar appearance] setBarStyle:UIBarStyleBlack];
KCMainViewController *mainController = [[KCMainViewController alloc] init];
_window.rootViewController = mainController;
[_window makeKeyAndVisible];
// 註冊推送通知(iOS 8 註冊方式有變)
[application registerUserNotificationSettings:
[UIUserNotificationSettings settingsForTypes:
UIUserNotificationTypeAlert |
UIUserNotificationTypeBadge |
UIUserNotificationTypeSound
categories:nil]];
[application registerForRemoteNotifications];
return YES;
}
// 註冊成功後在此接收裝置令牌
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
[self addDeviceToken:deviceToken];
NSLog(@"device token: %@", deviceToken);
}
- (void)application:(UIApplication *)application
didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
NSLog(@"didFailToRegisterForRemoteNotificationsWithError: %@",
error.localizedDescription);
[self addDeviceToken:nil];
}
- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo {
NSLog(@"receiveRemoteNotification, userInfo is %@", userInfo);
}
#pragma mark - 私有方法
/**
* 將裝置令牌同步到伺服器
*/
- (void)addDeviceToken:(NSData *)deviceToken {
NSString *key = @"DeviceToken";
NSData *oldToken = [[NSUserDefaults standardUserDefaults] objectForKey:key;
// 與已儲存的令牌不同時才上報
if (![oldToken isEqualToData:deviceToken]) {
[[NSUserDefaults standardUserDefaults] setObject:deviceToken forKey:key];
[self sendDeviceTokenWidthOldDeviceToken:oldToken newDeviceToken:deviceToken];
}
}
- (void)sendDeviceTokenWidthOldDeviceToken:(NSData *)oldToken
newDeviceToken:(NSData *)newToken {
// 注意確保真機能正常存取此位址
NSString *urlStr = @"https://192.168.1.101/RegisterDeviceToken.aspx";
urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:urlStr];
NSMutableURLRequest *requestM = [NSMutableURLRequest requestWithURL:url
cachePolicy:0
timeoutInterval:10.0];
[requestM setHTTPMethod:@"POST"];
NSString *bodyStr = [NSString stringWithFormat:@"oldToken=%@&newToken=%@",
oldToken, newToken];
[requestM setHTTPBody:[bodyStr dataUsingEncoding:NSUTF8StringEncoding]];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask =
[session dataTaskWithRequest:requestM
completionHandler:^(NSData *data,
NSURLResponse *response,
NSError *error) {
if (error) {
NSLog(@"Send failure, error is: %@", error.localizedDescription);
} else {
NSLog(@"Send Success!");
}
}];
[dataTask resume];
}
@end
這裡用一個 ASP.NET 頁面接收令牌,並寫入資料表的 Device 表(欄位為 AppID 與 DeviceToken)。若同時帶了舊令牌,先刪舊再寫新。
using System;
using System.Web;
using System.Web.UI;
using CMJ.Framework.Data;
namespace WebServer {
public partial class RegisterDeviceToken : System.Web.UI.Page {
private string _appID = @"com.cmjstudio.pushnotification";
private SqlHelper _helper = new SqlHelper();
protected void Page_Load(object sender, EventArgs e) {
try {
string oldToken = Request["oldToken"] + "";
string newToken = Request["newToken"] + "";
string sql = "";
// 有舊令牌則先刪除
if (oldToken != "") {
sql = string.Format(
"DELETE FROM dbo.Device WHERE AppID='{0}' AND DeviceToken='{1}';",
_appID, oldToken);
}
// 不存在則寫入
sql += string.Format(
@"IF NOT EXISTS (SELECT ID FROM dbo.Device
WHERE AppID='{0}' AND DeviceToken='{1}')
INSERT INTO dbo.Device (AppID, DeviceToken)
VALUES (N'{0}', N'{1}');", _appID, newToken);
_helper.ExecuteNonQuery(sql);
Response.Write("註冊成功!");
} catch (Exception ex) {
Response.Write("註冊失敗,錯誤詳情:" + ex.ToString());
}
}
}
}
實務上請改用參數化查詢,避免直接拼接字串造成 SQL injection 風險。
要對 APNs 發訊息,必須依 Apple 的標準格式組織內容。好在已有成熟開源套件可用,這裡以 Push Sharp 為例(它同時支援 Android、Windows Phone 等平台)。另外提醒一個關鍵細節:伺服器端使用的憑證,必須由「APNs Development iOS」類型憑證導出的 .p12 金鑰,一般 iOS Development 憑證導出的金鑰無法用於推送。
private void SendMessage(List<string> deviceToken, string message) {
// 建立推送物件
var pusher = new PushBroker();
pusher.OnNotificationSent += pusher_OnNotificationSent;
pusher.OnNotificationFailed += pusher_OnNotificationFailed;
pusher.OnChannelCreated += pusher_OnChannelCreated;
pusher.OnChannelDestroyed += pusher_OnChannelDestroyed;
pusher.OnChannelException += pusher_OnChannelException;
pusher.OnDeviceSubscriptionChanged += pusher_OnDeviceSubscriptionChanged;
pusher.OnDeviceSubscriptionExpired += pusher_OnDeviceSubscriptionExpired;
pusher.OnNotificationRequeue += pusher_OnNotificationRequeue;
pusher.OnServiceException += pusher_OnServiceException;
// 註冊推送服務(憑證為推送憑證導出的 .p12)
byte[] certificateData = File.ReadAllBytes(@"E:\KenshinCui_Push.p12");
pusher.RegisterAppleService(new ApplePushChannelSettings(certificateData, "123"));
foreach (string token in deviceToken) {
// 對指定裝置發送訊息
pusher.QueueNotification(new AppleNotification()
.ForDeviceToken(token)
.WithAlert(message)
.WithBadge(1)
.WithSound("default"));
}
}
void pusher_OnNotificationSent(object sender, PushSharp.Core.INotification notification) {
Console.WriteLine("訊息發送成功!");
}
void pusher_OnNotificationFailed(object sender, PushSharp.Core.INotification notification,
Exception error) {
Console.WriteLine("訊息發送失敗,錯誤詳情:" + error.ToString());
}
void pusher_OnServiceException(object sender, Exception error) {
Console.WriteLine("服務例外:" + error.ToString());
}
取令牌時記得把 APNs 傳回的格式整理乾淨——去掉角括號與空白,否則推送會失敗:
deviceTokens.Add((dr["DeviceToken"] + "").TrimStart('<').TrimEnd('>').Replace(" ", ""));
完成以上幾步,伺服器就能把訊息送到 APNs,iOS 端也能順利收到。
真機除錯與上架都需要申請多種憑證,初學者常搞不清楚彼此關係,這裡簡單說明。
憑證(Certificate):分開發憑證與發佈憑證,兩者都是真機除錯與上架的基本配備。開發憑證又分一般開發憑證與推送憑證;發佈憑證則有一般發佈憑證、推送憑證、Pass Type ID 憑證、網站發佈憑證、VoIP 服務憑證與蘋果支付憑證。用到特殊服務時必須選對應憑證。
應用標識(App ID):應用的唯一標識,對應 Bundle Identifier。分萬用應用 ID(可用於多個不同標識的普通應用)與明確應用 ID;使用消息推送、Passbook、iCloud 等服務時必須用明確 App ID。
裝置標識(UDID):標識每一台硬體裝置。注意它不是 device token——device token 是由 UDID 經蘋果自家演算法生成的一組識別碼。
配置簡介(Provisioning Profile,PP 檔):把 UDID、App ID 與開發憑證打包在一起的配置檔,同樣分開發與發佈兩類。
金鑰(.p12):申請開發憑證時需先提交憑證簽章要求檔。若只在該 Mac 上開發,下載憑證與配置檔即可;若要在其他機器開發,或伺服器端要對 APNs 發送訊息,就必須把憑證中的金鑰導出為 .p12 檔再匯入。
很多初學者會把本地通知、推送通知與「通知中心」混為一談。其實它們完全無關,甚至不屬於同一個框架:前者屬於 UIKit,通知中心屬於 Foundation。
通知中心(NSNotificationCenter)是應用「內部」的一種廣播機制,目的是讓 App 內不同物件之間解耦。它基於觀察者模式實作,無法跨進程通訊;收到訊息後,會依內部的通知分發表把訊息轉給訂閱者。
其實我們很早就用過它。應用生命週期相關的通知——啟動完成、進入後台、回到前台、取得或失去焦點——都是透過通知中心派送的:
- (void)viewDidLoad {
[super viewDidLoad];
[self addObserverToNotificationCenter];
}
#pragma mark 新增監聽
- (void)addObserverToNotificationCenter {
/* 監聽應用進入後台
* observer:監聽者
* selector:收到通知後執行的方法
* name:通知名稱(此處為系統常數)
* object:通知發送者,傳 nil 則接收任何物件發出的通知
*/
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(applicationEnterBackground)
name:UIApplicationDidEnterBackgroundNotification
object:[UIApplication sharedApplication]];
/* 監聽應用取得焦點
* queue:操作佇列,指定非主線程佇列即可非同步執行 block
* block:收到通知後執行的操作
*/
NSOperationQueue *operationQueue = [[NSOperationQueue alloc] init];
[[NSNotificationCenter defaultCenter]
addObserverForName:UIApplicationDidBecomeActiveNotification
object:[UIApplication sharedApplication]
queue:operationQueue
usingBlock:^(NSNotification *note) {
NSLog(@"Application become active.");
}];
}
- (void)applicationEnterBackground {
NSLog(@"Application enter background.");
}
更常見的用法是自訂通知來傳遞參數。以下示範:登入頁登入成功後發出通知,主頁收到後更新 UI。
// KCMainViewController.m
#define UPDATE_LOGIN_INFO_NOTIFICATION @"updateLoginInfo"
@interface KCMainViewController () {
UILabel *_lbLoginInfo;
UIButton *_btnLogin;
}
@end
@implementation KCMainViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self setupUI];
}
- (void)loginOut {
[self addObserverToNotification];
KCLoginViewController *loginController = [[KCLoginViewController alloc] init];
[self presentViewController:loginController animated:YES completion:nil];
}
- (void)addObserverToNotification {
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(updateLoginInfo:)
name:UPDATE_LOGIN_INFO_NOTIFICATION
object:nil];
}
// 可從通知物件讀取附加資訊
- (void)updateLoginInfo:(NSNotification *)notification {
NSDictionary *userInfo = notification.userInfo;
_lbLoginInfo.text = userInfo[@"loginInfo"];
_btnLogin.titleLabel.text = @"註銷";
}
- (void)dealloc {
// 記得移除監聽,否則可能導致 crash
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
// KCLoginViewController.m
#define UPDATE_LOGIN_INFO_NOTIFICATION @"updateLoginInfo"
- (void)login {
if ([_txtUserName.text isEqualToString:@"kenshincui"] &&
[_txtPassword.text isEqualToString:@"123"]) {
[self postNotification];
[self dismissViewControllerAnimated:YES completion:nil];
} else {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"系統資訊"
message:@"使用者名稱或密碼錯誤,請重新輸入!"
delegate:nil
cancelButtonTitle:@"取消"
otherButtonTitles:nil];
[alertView show];
}
}
// 送出通知,這裡帶上了附加資訊
- (void)postNotification {
NSDictionary *userInfo = @{
@"loginInfo": [NSString stringWithFormat:@"Hello, %@!", _txtUserName.text]
};
NSNotification *notification =
[NSNotification notificationWithName:UPDATE_LOGIN_INFO_NOTIFICATION
object:self
userInfo:userInfo];
[[NSNotificationCenter defaultCenter] postNotification:notification];
// 也可直接:
// [[NSNotificationCenter defaultCenter] postNotificationName:UPDATE_LOGIN_INFO_NOTIFICATION
// object:self
// userInfo:userInfo];
}
@end
通知中心與委派模式異曲同工,都是為了降低耦合。差別在於一對多:一個通知可以同時送給多個監聽者,而一個物件的 delegate 只能有一個。反過來說,委派也有它的優勢——程式碼分佈結構更清楚,不像通知那樣到處都能訂閱,資料流向更容易追。實務上並沒有絕對答案,需要依情境權衡:事件只有單一處理者、且關係明確時用委派;事件需要廣播給多個互不相識的元件時用通知中心。
另外别忘了,無論哪一種通知,在 dealloc 中移除監聽都是必須的;本地通知也要在時機到來後主動取消,否則會持續佔用系統那 64 個名額。