本地推送的骨架其實只有三件事:排入一則通知、在 App 內攔下它、需要的時候把它取消。以下逐步示範。
// 建立一個本地推送物件
UILocalNotification *notification = [[[UILocalNotification alloc] init] autorelease];
// 設定 10 秒之後觸發
NSDate *pushDate = [NSDate dateWithTimeIntervalSinceNow:10];
if (notification != nil) {
notification.fireDate = pushDate; // 觸發時間
notification.timeZone = [NSTimeZone defaultTimeZone]; // 時區
notification.repeatInterval = kCFCalendarUnitDay; // 重複間隔
notification.soundName = UILocalNotificationDefaultSoundName; // 提示音
notification.alertBody = @"推送內容";
notification.applicationIconBadgeNumber = 1; // 圖示紅圈數字
// 塞 userInfo,之後要撤銷時靠它辨識
NSDictionary *info = [NSDictionary dictionaryWithObject:@"name" forKey:@"key"];
notification.userInfo = info;
// 排入系統
UIApplication *app = [UIApplication sharedApplication];
[app scheduleLocalNotification:notification];
}
當通知觸發時,若 App 正好在前景,系統會走這個 delegate:
- (void)application:(UIApplication *)application
didReceiveLocalNotification:(UILocalNotification *)notification {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"iWeibo"
message:notification.alertBody
delegate:nil
cancelButtonTitle:@"確定"
otherButtonTitles:nil];
[alert show];
// 圖示上的數字減 1
application.applicationIconBadgeNumber -= 1;
}
把 key 寫進 userInfo 的用意就在這裡——取消時可以精準找到目標,不必把全部通知都清掉:
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;
}
}
一是角標數字不會自動歸零。使用者把通知按掉之後,圖示上的紅字還在,記得在 applicationDidBecomeActive: 裡主動設為 0。
二是 userInfo 一定要放可辨識的標識。等到要取消特定通知時,你會很慶幸自己當初多寫了那一行。
以上就是本地推送的三個基本動作。