iOS之本地通知 NSLocalNotification

      iOS 推送通知分爲本地推送和遠程推送通知,遠程推送通知就相似於咱們平時使用微信時,即便鎖屏了,也能收到好友發送給咱們的消息,而後在主屏幕顯示一個alertview,遠程推送須要遠程服務端的支持,比較複雜. 本地推送相對比較簡單,不須要服務端的支持。 微信

       本地通知是NSLocalNotification 實現的,經過實例化一個NSLocalNotification類型的通知,同時設置通知的fireDate 屬性,即通知的觸發時間;設置timeZone屬性,即時區;設置alertBody,顯示的內容;設置alertAction;設置soundName,即推送發生時的聲音;設置applicationIconBadgeNumber,即圖標上的數字;設置userInfo屬性,該屬性是一個NSDictionary類型的變量。而後在使用UIApplication 的 實例方法scheduleLocalNotification:或 presentLocalNotificationNow: 推送通知。 app

      在Appdelegate的- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions中添加以下代碼: spa

NSDate * itemDate = [NSDate date];
    
    UILocalNotification * localNotif = [[UILocalNotification alloc] init];
    if(localNotif == nil)
        return ;
    localNotif.fireDate = [itemDate dateByAddingTimeInterval:60];
    NSLog(@"fireDate is %@",localNotif.fireDate);
    localNotif.timeZone = [NSTimeZone defaultTimeZone];
    localNotif.alertBody = [NSString stringWithFormat:NSLocalizedString(@"%@ in %i minutes", nil),item.eventName,minutesBefore];
    localNotif.alertAction = NSLocalizedString(@"View Details", nil);
    localNotif.soundName = UILocalNotificationDefaultSoundName;
    localNotif.applicationIconBadgeNumber = 1;
    
    NSDictionary * infoDict = [NSDictionary dictionaryWithObjectsAndKeys:item.eventName,ToDoItemKey,@"Local Push reveived while running",MessageTitleKey ,nil];
    localNotif.userInfo = infoDict;
    [[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
    NSLog(@"scheduledLocalNotifications are %@",[[UIApplication sharedApplication] scheduledLocalNotifications]);
 當應用程序收到本地推送通知是發調用Appdelegate的 -( void )application:( UIApplication *)application didReceiveLocalNotification:( UILocalNotification *)notification方法,在該方法中顯示通知的內容:

-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
    NSLog(@"application : didReceiveLocalNotificaiton:");
    NSString * itemName = [notification.userInfo objectForKey:ToDoItemKey];
    NSString * messageTitle = [notification.userInfo objectForKey:MessageTitleKey];
    [self _showAlert:itemName withTitle:messageTitle];
    NSLog(@"Receive Local Notification while the app is still running ...");
    NSLog(@"current notification is %@",notification);
    application.applicationIconBadgeNumber = notification.applicationIconBadgeNumber - 1;
}
-(void)_showAlert:(NSString *)pushmessage withTitle:(NSString *)title
{
    UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:title message:pushmessage delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
    [alertView show];
}
相關文章
相關標籤/搜索