做了很多有Push Notification和Locale Notification的app,來整理下開發的筆記。今天先說說Local Notification
在iOS4.0後Apple加入了Local Notification。這裏是NSLocaleNotification的Class Reference http://developer.apple.com/library/ios/#documentation/iPhone/Reference/UILocalNotification_Class/Reference/Reference.html
如何註冊一個Notification
UILocalNotification *localNotification = [[UILocalNotification alloc] init];
// 設置notification的屬性
localNotification.fireDate = [startTimePicker.picker.date dateByAddingTimeInterval:36000]; //出發時間
localNotification.alertBody = @"Time To Schedule Our Service"; // 消息內容
localNotification.repeatInterval = NSSecondCalendarUnit; // 重複的時間間隔
localNotification.soundName = UILocalNotificationDefaultSoundName; // 觸發消息時播放的聲音
localNotification.applicationIconBadgeNumber = 1; //應用程序Badge數目
//設置隨Notification傳遞的參數
NSDictionary *infoDict = [NSDictionary dictionaryWithObjectsAndKeys:@"reminder", @"notificationId", @"phone", txtPhone.text, nil];
localNotification.userInfo = infoDict;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification]; //註冊
[localNotification release]; //釋放
遍歷已經註冊的所有LocaleNotification
NSArray *notifications = [[UIApplication sharedApplication] scheduledLocalNotifications];
for (UILocalNotification *notification in notifications ) {
if( [[notification.userInfo objectForKey:@"source"] isEqualToString:@"dailyReminder"] ) {
[[UIApplication sharedApplication] cancelLocalNotification:notification];
break;
}
}
撤銷LocaleNotification
[[UIApplication sharedApplication] cancelAllLocalNotifications]; // 撤銷所有的Notification
[[UIApplication sharedApplication] cancelLocalNotification:notification]; // 撤銷某個Notificiation,若要刪除某個特定的Notification,則可以在UserInfo中加入標記,遍歷所有的Notification來刪除。
響應事件
當Notification被觸發後,你的應用需要對此作出反應。應用此時可能會處於以下幾個狀態:
- 在前臺運行 - 當應用在前臺運行時,則ApplicationDelegate的didReceiveLocalNotification會被調用。
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification { NSLog(@"Notification Body: %@", notification.alertBody); NSLog(@"%@", notification.userInfo); application.applicationIconBadgeNumber = notification.applicationIconBadgeNumber-1; }
- 在後臺運行 - 用戶可以看到類似Push Notification的提醒,若用戶選擇查看提醒詳情,則應用通過 ApplicationDelegate的didFinishLaunchingWithOptions進入
}- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { UILocalNotification *localNotification = [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey]; if (localNotification) { NSLog(@"Notification Body: %@",localNotification.alertBody); NSLog(@"%@", localNotification.userInfo); application.applicationIconBadgeNumber = localNotification.applicationIconBadgeNumber-1; } // set up everything else return YES;