//.h
//注册
+ (void)registerLocalNotification;
//推送
+ (UILocalNotification *)pushLocalNotificationFor:(NSString *)alertBody;
+ (UILocalNotification *)pushLocalNotificationFor:(NSString *)alertBody userInfo:(NSDictionary *)userInfo;
+ (UILocalNotification *)pushLocalNotificationFor:(NSString *)alertBody userInfo:(NSDictionary *)userInfo fireSinceNow:(NSTimeInterval)time;
//.m
//注册
+ (void)registerLocalNotification {
//ios8之后注册通知 和之前不一样
#ifdef __IPHONE_8_0
//ios8 注册本地通知
if ([UIApplication instancesRespondToSelector:@selector(registerUserNotificationSettings:)]) {
UIUserNotificationSettings *noteSetting =[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:noteSetting];
}
if ([[UIApplication sharedApplication]respondsToSelector:@selector(registerUserNotificationSettings:)]) {
UIUserNotificationSettings *setting = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound categories:nil];
[[UIApplication sharedApplication]registerUserNotificationSettings:setting];
}else {
UIRemoteNotificationType myType = UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound;
[[UIApplication sharedApplication]registerForRemoteNotificationTypes:myType];
}
#else
#endif
}
//推送
+ (UILocalNotification *)pushLocalNotificationFor:(NSString *)alertBody {
//在ios下应用分为两种不同的Notification种类
//1.本地 //2.远程(APNS)
//本地 Notification 是由ios系统下NotificationManger统一管理.只需要将组装好的本地通知对象添加到系统的Notification管理队列,系统就会在指定的时间激发该通知
//本地通知 只能在前台和后台触发,不能在其他状态下激发
//本地 流程
//1.1创建一个本地通知对象
UILocalNotification *localNotification = [[UILocalNotification alloc]init];
//调度
//1.2 时间上的调度
//fireDate 就是激发的准确时间
localNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:1.0];
//timeZone 是通知激发的时间是否根据时区的改变而改变,如果是nil,通知会在一段时间后激发,而不是某一确切的时间被激发
//repeatInteval 被重复激发的时间,时间差会根据日历单位,例如每周,如果不设置,将会被重复
//1.3 内容
localNotification.alertBody = kSTR(@"%@", alertBody);
//1.4其他内容
UIApplication *app = [UIApplication sharedApplication];
app.applicationIconBadgeNumber ++;
//最后一步
//注册
[[UIApplication sharedApplication]scheduleLocalNotification:localNotification];
return localNotification;
}
+ (UILocalNotification *)pushLocalNotificationFor:(NSString *)alertBody userInfo:(NSDictionary *)userInfo {
UILocalNotification *mzLocalNotification = [self pushLocalNotificationFor:alertBody];
mzLocalNotification.userInfo = userInfo;
return mzLocalNotification;
}
+ (UILocalNotification *)pushLocalNotificationFor:(NSString *)alertBody userInfo:(NSDictionary *)userInfo fireSinceNow:(NSTimeInterval)time {
UILocalNotification *mzLocalNotification = [self pushLocalNotificationFor:alertBody userInfo:userInfo];
mzLocalNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:time];
return mzLocalNotification;
}
谢谢阅读!