iOS開發之UILocalNotification本地通知

在實際iOS開發中,都會用到,iOS的通知有本地通知和遠程通知兩種。

在這裏介紹一下iOS下如何使用UILocalNotification進行應用程序的本地通知,基本上大部分的app都會有這個功能。

(1)本地通知中心發送消息:


UILocalNotification *notification=[[UILocalNotification alloc] init];
    if (notification!=nil) {
        
        NSDate *now=[NSDate new];
        notification.fireDate=[now dateByAddingTimeInterval:6]; //觸發通知的時間
        notification.repeatInterval=0; //循環次數,kCFCalendarUnitWeekday一週一次
        
        notification.timeZone=[NSTimeZone defaultTimeZone];
        notification.soundName = UILocalNotificationDefaultSoundName;
        notification.alertBody=@"<span style="font-family:Microsoft YaHei;">到時間泡妞去</span>!";
        
        notification.alertAction = @"打開";  //提示框按鈕
        notification.hasAction = YES; //是否顯示額外的按鈕,爲no時alertAction消失
        
        notification.applicationIconBadgeNumber = 1; //設置app圖標右上角的數字
        
        //下面設置本地通知發送的消息,這個消息可以接受
        NSDictionary* infoDic = [NSDictionary dictionaryWithObject:@"value" forKey:@"key"];
        notification.userInfo = infoDic;
        //發送通知
        [[UIApplication sharedApplication] scheduleLocalNotification:notification];
    }

(2)接受本地通知發送的消息(在AppDelegate文件中)

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification*)notification{
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"LocalNotification" message:notification.alertBody delegate:nil cancelButtonTitle:@"確定" otherButtonTitles:nil];
    [alert show];
    
    NSDictionary* dic = [[NSDictionary alloc]init];
    //這裏可以接受到本地通知中心發送的消息
    dic = notification.userInfo;
    NSLog(@"user info = %@",[dic objectForKey:@"key"]);
    
    // 圖標上的數字<span style="font-family:Microsoft YaHei;">+</span>1
    application.applicationIconBadgeNumber <span style="font-family:Microsoft YaHei;">+</span>= 1;
}
							
- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
    
    // 圖標上的數字減1
    application.applicationIconBadgeNumber -= 1;
}

大家可以在自己的項目中使用!
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章