在iOS8之后,以前的本地推送写法可能会出错,接收不到推送的信息,
如果出现以下信息:
说明在IOS8下没有注册,所以需要额外添加对IOS8的注册方法,API中有下面这个方法:
- - (void)registerUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings NS_AVAILABLE_IOS(8_0);
这个方法是8.0之后才能使用的,所以需要判断一下系统的版本。
第一步:注册本地通知:
- + (void)registerLocalNotification:(NSInteger)alertTime {
- UILocalNotification *notification = [[UILocalNotification alloc] init];
-
- NSDate *fireDate = [NSDate dateWithTimeIntervalSinceNow:alertTime];
- NSLog(@"fireDate=%@",fireDate);
-
- notification.fireDate = fireDate;
-
- notification.timeZone = [NSTimeZone defaultTimeZone];
-
- notification.repeatInterval = kCFCalendarUnitSecond;
-
-
- notification.alertBody = @"该起床了...";
- notification.applicationIconBadgeNumber = 1;
-
- notification.soundName = UILocalNotificationDefaultSoundName;
-
- NSDictionary *userDict = [NSDictionary dictionaryWithObject:@"开始学习iOS开发了" forKey:@"key"];
- notification.userInfo = userDict;
-
-
- if ([[UIApplication sharedApplication] respondsToSelector:@selector(registerUserNotificationSettings:)]) {
- UIUserNotificationType type = UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound;
- UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:type
- categories:nil];
- [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
-
- notification.repeatInterval = NSCalendarUnitDay;
- } else {
-
- notification.repeatInterval = NSDayCalendarUnit;
- }
-
-
- [[UIApplication sharedApplication] scheduleLocalNotification:notification];
- }
第二步:处理通知,这个是在appdelegate中的代理 方法回调
- - (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
- NSLog(@"noti:%@",notification);
-
-
-
- NSString *notMess = [notification.userInfo objectForKey:@"key"];
- UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"本地通知(前台)"
- message:notMess
- delegate:nil
- cancelButtonTitle:@"OK"
- otherButtonTitles:nil];
- [alert show];
-
-
- NSInteger badge = [UIApplication sharedApplication].applicationIconBadgeNumber;
- badge--;
- badge = badge >= 0 ? badge : 0;
- [UIApplication sharedApplication].applicationIconBadgeNumber = badge;
-
-
- [HomeViewController cancelLocalNotificationWithKey:@"key"];
- }
第三步:在需要的时候取消某个推送
- + (void)cancelLocalNotificationWithKey:(NSString *)key {
-
- NSArray *localNotifications = [UIApplication sharedApplication].scheduledLocalNotifications;
-
- for (UILocalNotification *notification in localNotifications) {
- NSDictionary *userInfo = notification.userInfo;
- if (userInfo) {
-
- NSString *info = userInfo[key];
-
-
- if (info != nil) {
- [[UIApplication sharedApplication] cancelLocalNotification:notification];
- break;
- }
- }
- }
- }
下载demo:https://github.com/632840804/LocalPush