這兩天在做一個日程提醒功能,用到了本地通知的功能,記錄相關知識如下:
1、本地通知的定義和使用:
本地通知是UILocalNotification的實例,主要有三類屬性:
scheduled time,時間周期,用來指定iOS系統發送通知的日期和時間;
notification type,通知類型,包括警告信息、動作按鈕的標題、應用圖標上的badge(數字標記)和播放的聲音;
自定義數據,本地通知可以包含一個dictionary類型的本地數據。
對本地通知的數量限制,iOS最多允許最近本地通知數量是64個,超過限制的本地通知將被iOS忽略。
代碼如下 |
復制代碼 |
UILocalNotification *localNotification = [[UILocalNotification alloc] init]; if (localNotification == nil) { return; } //設置本地通知的觸發時間(如果要立即觸發,無需設置),這里設置為20妙后 localNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:20]; //設置本地通知的時區 localNotification.timeZone = [NSTimeZone defaultTimeZone]; //設置通知的內容 localNotification.alertBody = affair.title; //設置通知動作按鈕的標題 localNotification.alertAction = @"查看”; //設置提醒的聲音,可以自己添加聲音文件,這里設置為默認提示聲 localNotification.soundName = UILocalNotificationDefaultSoundName; //設置通知的相關信息,這個很重要,可以添加一些標記性內容,方便以后區分和獲取通知的信息 NSDictionary *infoDic = [NSDictionary dictionaryWithObjectsAndKeys:LOCAL_NOTIFY_SCHEDULE_ID,@"id",[NSNumber numberWithInteger:time],@"time",[NSNumber numberWithInt:affair.aid],@"affair.aid", nil]; localNotification.userInfo = infoDic; //在規定的日期觸發通知 [[UIApplication sharedApplication] scheduleLocalNotification:localNotification]; //立即觸發一個通知 // [[UIApplication sharedApplication] presentLocalNotificationNow:localNotification]; [localNotification release]; |
2、取消本地通知:
代碼如下 |
復制代碼 |
//取消某一個通知 NSArray *notificaitons = [[UIApplication sharedApplication] scheduledLocalNotifications]; //獲取當前所有的本地通知 if (!notificaitons || notificaitons.count <= 0) { return; } for (UILocalNotification *notify in notificaitons) { if ([[notify.userInfo objectForKey:@"id"] isEqualToString:LOCAL_NOTIFY_SCHEDULE_ID]) { //取消一個特定的通知 [[UIApplication sharedApplication] cancelLocalNotification:notify]; break; } } //取消所有的本地通知 [[UIApplication sharedApplication] cancelAllLocalNotifications]; |
3、本地通知的響應:
如果已經注冊了本地通知,當客戶端響應通知時:
a、應用程序在后台的時候,本地通知會給設備送達一個和遠程通知一樣的提醒,提醒的樣式由用戶在手機設置中設置
b、應用程序正在運行中,則設備不會收到提醒,但是會走應用程序delegate中的方法:
代碼如下 |
復制代碼 |
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification { } |
,如果你想實現程序在后台時候的那種提醒效果,可以在上面這個方法中添加相關代碼,示例代碼:
代碼如下 |
復制代碼 |
if ([[notification.userInfo objectForKey:@"id"] isEqualToString:@"affair.schedule"]) { UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"test" message:notification.alertBody delegate:nil cancelButtonTitle:@"關閉" otherButtonTitles:notification.alertAction, nil nil]; [alert show]; } |
需要注意的是,在情況a中,如果用戶點擊提醒進入應用程序,也會執行收到本地通知的回調方法,這種情況下如果你添加了上面那段代碼,則會出現連續出現兩次提示,為了解決這個問題,修改代碼如下:
代碼如下 |
復制代碼 |
if ([[notification.userInfo objectForKey:@"id"] isEqualToString:@"affair.schedule"]) { //判斷應用程序當前的運行狀態,如果是激活狀態,則進行提醒,否則不提醒 if (application.applicationState == UIApplicationStateActive) { UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"test" message:notification.alertBody delegate:nil cancelButtonTitle:@"關閉" otherButtonTitles:notification.alertAction, nil nil]; [alert show]; } } |