本地推送将会在状态栏里、锁屏界面等出现通知。现在以在状态栏里的通知为例。
1 -(void)alertLoaclNotification{ 2 //初始化一个 UILocalNotification 3 UILocalNotification * notification = [[UILocalNotification alloc] init]; 4 if (notification!=nil) { 5 // 设置通知的提醒时间 6 NSDate *currentDate = [NSDate date]; 7 notification.timeZone = [NSTimeZone defaultTimeZone]; // 使用本地时区 8 notification.fireDate = [currentDate dateByAddingTimeInterval:2.0]; 9 10 // 设置重复间隔 11 notification.repeatInterval = kCFCalendarUnitDay; 12 13 // 设置提醒的文字内容 14 notification.alertBody = @"该吃饭了"; 15 16 // 通知提示音 使用默认的 17 notification.soundName= UILocalNotificationDefaultSoundName; 18 19 // 设置应用程序右上角的红色提醒个数 20 notification.applicationIconBadgeNumber++; 21 22 // 设定通知的userInfo,用来标识该通知 23 NSDictionary * inforDic = [NSDictionary dictionaryWithObject:@"name" forKey:@"key"]; 24 notification.userInfo =inforDic; 25 26 // 将通知添加到系统中 27 [[UIApplication sharedApplication] scheduleLocalNotification:notification]; 28 } 29 }
取消本地通知时,则可以用
1 //拿到所有推送的数组 2 NSArray * array = [[UIApplication sharedApplication] scheduledLocalNotifications]; 3 //便利这个数组 根据 key 拿到我们想要的 UILocalNotification 4 for (UILocalNotification * loc in array) { 5 if ([[loc.userInfo objectForKey:@"key"] isEqualToString:@"name"]) { 6 //取消 本地推送 7 [[UIApplication sharedApplication] cancelLocalNotification:loc]; 8 } 9 }
在程序运行时,推送可能不出现,会提示
Attempting to badge the application icon but haven‘t received permission……
这出现在IOS8上,是没有权限的原因。若换成IOS7或以前的,则没这些问题。现在在IOS8中要实现badge、alert和sound等都需要用户同意才能,因为这些都算做Notification“通知”,为了防止有些应用动不动给用户发送“通知”骚扰用户,所以在iOS8时,这些“通知”必须要用户同意才行。
要在IOS8解决这些问题,就要弹出一个提示框,询问用户是否允许推送通知。具体就是在AppDelegate中的
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
方法中添加系统判断
1 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 2 { 3 //判断系统版本 4 CGFloat sysVersion=[[UIDevice currentDevice]systemVersion].floatValue; 5 if (sysVersion>=8.0) { 6 UIUserNotificationType type = UIUserNotificationTypeBadge | UIUserNotificationTypeAlert | UIUserNotificationTypeSound; 7 UIUserNotificationSettings *setting = [UIUserNotificationSettings settingsForTypes:type categories:nil]; 8 [[UIApplication sharedApplication] registerUserNotificationSettings:setting]; 9 } 10 return YES; 11 }
时间: 2024-10-29 07:03:48