UILocalNotification實現本地的鬧鍾提醒


iOS下的Notification的使用

 

在iOS下應用分為兩種不同的Notification種類,本地和遠程。

下面主要介紹本地的Notification:

本地的Notification由iOS下NotificationManager統一管理,所使用的對象是UILocalNotification,

UILocalNotification的屬性涵蓋了所有處理Notification需要的內容。

屬性有fireDate、timeZone、repeatInterval、repeatCalendar、alertBody、alertAction、hasAction、alertLaunchImage、applicationIconBadgeNumber、soundName和userInfo。

其中fireDate、timeZone、repeatInterval和repeatCalendar是用於UILocalNotification的調度。fireDate是UILocalNotification的激發的確切時間。

timeZone是UILocalNotification激發時間是否根據時區改變而改變,如果設置為nil的話,那么UILocalNotification將在一段時候后被激發,而不是某一個確切時間被激發。

repeatInterval是UILocalNotification被重復激發之間的時間差,不過時間差是完全根據日歷單位(NSCalendarUnit)的,例如每周激發的單位,NSWeekCalendarUnit,如果不設置的話,將不會重復激發。

repeatCalendar是UILocalNotification重復激發所使用的日歷單位需要參考的日歷,如果不設置的話,系統默認的日歷將被作為參考日歷。

alertBody、alertAction、hasAction和alertLaunchImage是當應用不在運行時,系統處理。

alertBody是一串現實提醒內容的字符串(NSString),如果alertBody未設置的話,Notification被激發時將不現實提醒。

alertAction也是一串字符(NSString),alertAction的內容將作為提醒中動作按鈕上的文字,如果未設置的話,提醒信息中的動作按鈕將顯示為“View”相對文字形式。

alertLaunchImage是在用戶點擊提醒框中動作按鈕(“View”)時,等待應用加載時顯示的圖片,這個將替代應用原本設置的加載圖片。

hasAction是一個控制是否在提醒框中顯示動作按鈕的布爾值,默認值為YES。

applicationIconBadgeNumber是顯示在應用圖標右上角的數字,這樣讓用戶直接了解到應用需要處理的Notification。

soundName是另一個UILocalNotification用來提醒用戶的手段,在Notification被激發之后將播放這段聲音來提醒用戶有Notification需要處理,如果不設soundName的話,Notification被激發是將不會有聲音播放,除去應用特制的聲音以外,也可以將soundName設為UILocalNotificationDefaultSoundName來使用系統默認提醒聲音。

userInfo是Notification用來傳遞數據的NSDictionary。

 

以下內容先參考網上介紹的方法理解,然后總結項目封裝類便於使用。

1.

        在項目需要開啟定時提醒的地方設置UILocalNotification對象,

         在系統Notification處理隊列中登記已設置完的UILocalNotification對象:

       NSInteger period = 7200;//設置喚醒期間 60*60*2 兩個小時后提醒

    UILocalNotification *notification=[[UILocalNotification alloc] init];
        if (notification!=nil)  {
            
            NSDate *now=[NSDate new];
           
            //notification.fireDate=[now addTimeInterval:period];
            notification.fireDate = [now dateByAddingTimeInterval:period];
            NSLog(@"%d",period);
            notification.timeZone=[NSTimeZone defaultTimeZone];
            notification.soundName = @"ping.caf";
            //notification.alertBody=@"TIME!";
            
            notification.alertBody = [NSString stringWithFormat:@"@%時間到了!",nameStr];
            
            NSDictionary* info = [NSDictionary dictionaryWithObject:uniqueCodeStr forKey:CODE];
            notification.userInfo = info;


            /**

      在設置完UILocalNotification對象之后,應用需要在系統Notification處理隊列中登記

      已設置完的UILocalNotification對象。

    */
            [[UIApplication sharedApplication] scheduleLocalNotification:notification];      
            
        } 

        [notification release];

如果你的應用程序處於關閉狀態,設置的時間到了,會自動在桌面彈出一個提示框,點顯示后,

就可以啟動軟件。然后在這里對lanchOptions進行處理,找到它里面的信息,就可以拿到設置時的

需要處理的東西,就可以繼續操作了。

    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:

       (NSDictionary *)launchOptions {

        UILocalNotification *localNotif =

               [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];
        if (localNotif) {

            NSLog(@"Recieved Notification %@",localNotif);
            NSDictionary* infoDic = localNotif.userInfo;
            NSLog(@"userInfo description=%@",[infoDic description]);
            NSString* codeStr = [infoDic objectForKey:CODE];
        }
  }


如果此時你的客戶端 軟件處於打開狀態,則會調用
 - (void)application:(UIApplication *)app didReceiveLocalNotification:(UILocalNotification *)notif {

    //同上一樣的處理方法一樣的處理方法。

          if (notif) {

            NSLog(@"Recieved Notification %@",notif);
            NSDictionary* infoDic = notif.userInfo;
            NSLog(@"userInfo description=%@",[infoDic description]);
            NSString* codeStr = [infoDic objectForKey:CODE];
        }

  }

 以下兩個方式來取消一個已經登記的Notification

 第一個方式可以直接取消一個指定的Notification:

  NSString *myIDToCancel = @"some_id_to_cancel"; 
  UILocalNotification *notificationToCancel=nil; 
    for(UILocalNotification *aNotif in [[UIApplication sharedApplication] scheduledLocalNotifications]) {   
    if([aNotif.userInfo objectForKey:@"ID"] isEqualToString:myIDToCancel]) {      
      notificationToCancel=aNotif;    
        break;   
    } 
    } 
  [[UIApplication sharedApplication] cancelLocalNotification:notificationToCancel];

 第二個方式將會把該應用已登記的Notification一起取消:

 [[UIApplication sharedApplication] cancelAllLocalNotification];

 

2.

  為了便於管理和使用,可以將UILocalNotification封裝在單獨的類中進行使用:

 

//  LocalNotificationsManager.h 文件內容

#import <Foundation/Foundation.h>

 @interface LocalNotificationsManager : NSObject

 + (void)addLocalNotificationWithFireDate:(NSDate *)date 

                              activityId:(NSInteger)aid 

                           activityTitle:(NSString *)title;

 

+ (BOOL)removeLocalNotificationWithActivityId:(NSInteger)aid;

 @end

 

//  LocalNotificationsManager.m 文件內容

 #import "LocalNotificationsManager.h"

 @implementation LocalNotificationsManager

 + (void)addLocalNotificationWithFireDate:(NSDate *)date       //設置提醒

                              activityId:(NSInteger)aid 

                           activityTitle:(NSString *)title {

    NSDate *t = [NSDatedateWithTimeIntervalSinceNow:7200.0f];      // 2*60*60 2h

    NSComparisonResult result = [t compare:date];

    if (result == -1) {

        UILocalNotification *notification=[[UILocalNotificationalloc] init]; 

        notification.fireDate = [date dateByAddingTimeInterval:-7200.0f]; 

        notification.timeZone = [NSTimeZone defaultTimeZone]; 

        notification.applicationIconBadgeNumber = 1;

        notification.soundName = UILocalNotificationDefaultSoundName;

        notification.alertBody = [NSString stringWithFormat:@"%@ 活動馬上就要開始了",title]; 

        NSDictionary *dic =

         [NSDictionarydictionaryWithObjectsAndKeys:[NSNumbernumberWithInt:aid], @"activityid", nil];

        notification.userInfo = dic;

        [[UIApplicationsharedApplication] scheduleLocalNotification:notification];

        [notification release];

    }

}

+ (BOOL)removeLocalNotificationWithActivityId:(NSInteger)aid //取消提醒

{

    UIApplication *application = [UIApplicationsharedApplication];

    NSArray *localNotifications = [[UIApplicationsharedApplication] scheduledLocalNotifications];

    for (UILocalNotification *obj in localNotifications) {

        NSInteger activityId = [[obj.userInfo objectForKey:@"activityid"] intValue];

        if (aid == activityId) {

            [application cancelLocalNotification:obj];

            return YES;

        }

    }

    returnNO;

}

 @end

 

使用方法:

導入  "LocalNotificationsManager.h"類

定時提醒

       [LocalNotificationsManageraddLocalNotificationWithFireDate:[NSDategetDateTimeFromString:self.creatorActivity.beginDate]    //beginDate(*NSString)

                                                         activityId:aid 

                                                      activityTitle:self.creatorActivity.activityName];

取消提醒

    [LocalNotificationsManagerremoveLocalNotificationWithActivityId:self.activity.activityID];

 

參考:http://hi.baidu.com/jackz1026/item/fee0f30d3ddea3cb75cd3c07 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM