- ios8发送本地通知,需要先注册本地通知。
-
if ([[UIApplication sharedApplication]currentUserNotificationSettings].types==UIUserNotificationTypeNone) 当前应用的本地通知类型,UIUserNotificationTypeNone没有注册本地通知 注册是系统级的,跟程序没有关系,当程序删除之后重新安装依然是授权过了,绑定了id。
//每次执行授权操作的时候,都会走这个代理 - (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings;
- UIUserNotificationTypeNone = 0, // 申请不得在收到通知时提出任何用户界面
- UIUserNotificationTypeBadge = 1 << 0, // 该应用程序可在收到通知时将其图标标记为
- UIUserNotificationTypeSound = 1 << 1, // 该应用程序可在收到通知后发出声音
- UIUserNotificationTypeAlert = 1 << 2, // 该应用程序可在收到通知后显示警报
- (对应标记,声音,横幅)
实际的开发分为两种情况
1.当应用程序退出到后台,通过点击推送进入程序。这个时候可以通过使用
-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification;
根据这个方法获取推送的信息。
2.当应用程序被杀死的时候,点击推送进来的时候会重新加载界面。
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions;
可以根据launchOptions获取推送内容。
//接收通知参数
UILocalNotification *notification=[launchOptions valueForKey:UIApplicationLaunchOptionsLocalNotificationKey];
-(void)addNotification{
UILocalNotification *notification=[[UILocalNotification alloc]init];
notification.fireDate=[NSDate dateWithTimeIntervalSinceNow:10];
notification.alertBody=@"通知来咯";
[[UIApplication sharedApplication]scheduleLocalNotification:notification];
}
实现一个小功能:当用户连续1小时不操作会通过本地推送提示用户操作,每隔1小时提示一次。
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
//通知授权
if ([[UIApplication sharedApplication]currentUserNotificationSettings].types==UIUserNotificationTypeNone) {
[[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound categories:nil]];
}
}
//失去焦点
-(void)applicationWillResignActive:(UIApplication *)application{
[self addNotification];
}
-(void)addNotification{
UILocalNotification *notification=[[UILocalNotification alloc]init];
notification.fireDate=[NSDate dateWithTimeIntervalSinceNow:10];
notification.alertBody=@"一分钟没有用了";
notification.repeatInterval=NSCalendarUnitMinute;//设置重复的频率
[[UIApplication sharedApplication]scheduleLocalNotification:notification];
}
//清空所有的本地通知
[[UIApplication sharedApplication]cancelAllLocalNotifications];