標籤:
如果使用者長時間沒有使用我們的APP,我們就需要提醒使用者來使用。這個本地通知就可以做到。
先說明一下我的解決思路:在AppDelegate裡面寫
1,註冊蘋果的通知
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { //註冊蘋果的通知 UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeBadge |UIUserNotificationTypeSound |UIUserNotificationTypeAlert) categories:nil]; [[UIApplication sharedApplication] registerUserNotificationSettings:settings]; return YES; }
2,當使用者退出app時建立一個通知,一定時間後調用,比如10秒。
//進入後台響應的方法 - (void)applicationDidEnterBackground:(UIApplication *)application{ // 初始化本地通知對象 UILocalNotification *notification = [[UILocalNotification alloc] init]; if (notification) { // 設定通知的提醒時間 NSDate *currentDate = [NSDate date]; notification.timeZone = [NSTimeZone defaultTimeZone]; // 使用本地時區 notification.fireDate = [currentDate dateByAddingTimeInterval:10]; // 設定提醒的文字內容 notification.alertBody = @"您一周都沒有關注寶寶了,快來看看!"; notification.alertAction = NSLocalizedString(@"關心寶寶", nil); // 通知提示音 使用預設的 notification.soundName= UILocalNotificationDefaultSoundName; // 設定應用程式右上方的提醒個數 notification.applicationIconBadgeNumber++; // 設定通知的userInfo,用來標識該通知 NSDictionary *dict =[NSDictionary dictionaryWithObjectsAndKeys:@"notification",@"nfkey",nil]; [notification setUserInfo:dict]; // 將通知添加到系統中 [[UIApplication sharedApplication] scheduleLocalNotification:notification]; } }
3,在收到通知,點擊進入應用的時候取消通知,講外面顯示的數字賦值為0,application.applicationIconBadgeNumber=0;
didReceiveLocalNotification是app在前台運行,通知時間到了,調用的方法。如果程式在後台運行,時間到了以後是不會走這個方法的。
applicationDidBecomeActive是app在後台運行,通知時間到了,你從通知欄進入,或者直接點app表徵圖進入時,會走的方法。
- (void)applicationDidBecomeActive:(UIApplication *)application { application.applicationIconBadgeNumber=0; }
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{ application.applicationIconBadgeNumber=0; //取消通知 for (UILocalNotification *noti in [application scheduledLocalNotifications]) { NSString *notiID = [noti.userInfo objectForKey:@"nfkey"]; if ([notiID isEqualToString:@"notification"]) { [application cancelLocalNotification:noti]; } }}
4,當使用者在沒收到通知進入應用的時候取消通知。原因:當你第一次退出程式,就會建立一個通知a,10秒後推送,如果在這10秒內,重新登入退出又會建立 新的通知b,那麼我們會連續收到兩個通知。為了避免重複,在通知a時間還沒有到情況下登入app我們就取消通知a,退出時建立通知b。
- (void)applicationWillEnterForeground:(UIApplication *)application{ //取消所有通知 [application cancelAllLocalNotifications]; }
如果想要重複調用這個通知,
// 設定重複間隔
notification.repeatInterval = kCFCalendarUnitDay;參考:http://www.2cto.com/kf/201403/285612.html http://www.cnblogs.com/lan0725/p/3195263.htmldemo下載:https://github.com/wangdachui/WTUILocalNotification
iOS 本地通知