iOS 的推送通知可以分成兩類。遠程推送(Remote Notification)就像我們用微信時的體驗——即使 App 關閉、裝置鎖屏,好友送來的訊息仍然會跳出提示;它需要伺服器端配合,架構相對複雜。本地推送(Local Notification)則簡單得多,完全由裝置本身產生,不需要任何伺服器支援。
本地通知由 UILocalNotification 物件代表。使用流程是:建立一個通知物件,設定觸發時間(fireDate)、時區(timeZone)、顯示內容(alertBody)、動作文字(alertAction)、提示音(soundName)、圖示數字(applicationIconBadgeNumber)與附加資訊(userInfo),最後透過 UIApplication 的 scheduleLocalNotification: 或 presentLocalNotificationNow: 排入系統佇列。
// 建立通知物件
UILocalNotification *notification = [[[UILocalNotification alloc] init] autorelease];
// 設定為 10 秒後觸發
NSDate *pushDate = [NSDate dateWithTimeIntervalSinceNow:10];
if (notification != nil)
{
// 觸發時間
notification.fireDate = pushDate;
// 時區:設為 nil 時,通知會在「一段時間後」觸發,而非精確的某一刻
notification.timeZone = [NSTimeZone defaultTimeZone];
// 重複間隔,不設定則只觸發一次
notification.repeatInterval = kCFCalendarUnitDay;
// 提示音,不設定則靜音
notification.soundName = UILocalNotificationDefaultSoundName;
// 通知內容
notification.alertBody = @"推送內容";
// 啟動圖
notification.alertLaunchImage = [[NSBundle mainBundle] pathForResource:@"3" ofType:@"jpg"];
// 圖示上的紅色數字
notification.applicationIconBadgeNumber = 1;
// 附加資訊,之後要取消通知時可用來比對
NSDictionary *info = [NSDictionary dictionaryWithObject:@"name" forKey:@"key"];
notification.userInfo = info;
// 排入通知佇列,避免重複加入同一筆
UIApplication *app = [UIApplication sharedApplication];
BOOL status = YES;
for (UILocalNotification *noti in app.scheduledLocalNotifications)
{
if ([noti.userInfo objectForKey:@"key"])
{
status = NO;
}
}
if (status)
{
[app scheduleLocalNotification:notification];
}
}
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"iWeibo"
message:notification.alertBody
delegate:nil
cancelButtonTitle:@"確定"
otherButtonTitles:nil];
[alert show];
// 收到後把圖示數字減一
application.applicationIconBadgeNumber -= 1;
}
比對 userInfo 中的自訂 key,找出要取消的那一筆:
UIApplication *app = [UIApplication sharedApplication];
NSArray *localArray = [app scheduledLocalNotifications];
UILocalNotification *localNotification;
if (localArray)
{
for (UILocalNotification *noti in localArray)
{
NSDictionary *dict = noti.userInfo;
if (dict)
{
NSString *inKey = [dict objectForKey:@"key"];
if ([inKey isEqualToString:@"對應的key值"])
{
if (localNotification)
{
[localNotification release];
localNotification = nil;
}
localNotification = [noti retain];
break;
}
}
}
// 若找不到已存在的相同 key,就新建一個
if (!localNotification)
{
localNotification = [[UILocalNotification alloc] init];
}
if (localNotification)
{
[app cancelLocalNotification:localNotification];
[localNotification release];
return;
}
}