#pragma mark 本地通知测试
//在需要发送通知的类中实现下面两个方法
1.//注册一个本地通知
+(void)registerLocalNotification:(NSInteger)alertTime{
UILocalNotification *notifition = [[UILocalNotification alloc]init];
//设置触发时间
NSDate *fireDate = [NSDate dateWithTimeIntervalSinceNow:alertTime];
notifition.fireDate = fireDate;
//设置时区
notifition.timeZone = [NSTimeZone defaultTimeZone];
//设置重复间隔
notifition.repeatInterval = kCFCalendarUnitSecond;
//设置通知的内容
notifition.alertBody = @"该起床了......";
notifition.alertTitle = @"星期五不起床";
//通知被触发时播放的声音
notifition.soundName = UILocalNotificationDefaultSoundName;
//通知参数
notifition.userInfo = [NSDictionary dictionaryWithObject:@"好好学习,天天向上" forKey:@"swift"];
//这个方法是iOS8以后增加的
if ([[UIApplication sharedApplication] respondsToSelector:@selector(registerUserNotificationSettings:)]) {
UIUserNotificationType type = UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound;
UIUserNotificationSettings *setting = [UIUserNotificationSettings settingsForTypes:type categories:nil];
[[UIApplication sharedApplication]registerUserNotificationSettings:setting];
//通知重复提示单位,可以是天/周/月
notifition.repeatInterval = NSCalendarUnitDay;
}else{
notifition.repeatInterval = NSDayCalendarUnit;
}
//执行通知
[[UIApplication sharedApplication] scheduleLocalNotification:notifition];
}
2.//在需要的时候取消某个推送
+(void) cancelLocalNotifitionWithKey:(NSString *)key{
//获取本地通知数组
NSArray *localNotifitions = [UIApplication sharedApplication].scheduledLocalNotifications;
for (UILocalNotification *notifition in localNotifitions) {
NSDictionary *userInfo = notifition.userInfo;
if (userInfo) {
//根据设置通知参数时指定的key来获取通知参数
NSString *info = userInfo[@"key"];
if (info != nil) {
[[UIApplication sharedApplication] cancelLocalNotification:notifition];
break;
}
}
}
}
@end
static UIWindow *window_;
//处理通知,方法回调
-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification{
//获取通知所带数据
NSString *noMess = [notification.userInfo objectForKey:@"key"];
window_ = [[UIWindow alloc]init];
window_.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 20);
UILabel *label = [[UILabel alloc]init];
[label sizeToFit];
label.text = noMess;
label.textAlignment = NSTextAlignmentCenter;
window_.windowLevel = UIWindowLevelAlert; //设置window的优先级,使窗口显示时能够盖住状态栏
window_.backgroundColor = [UIColor yellowColor];
window_.hidden = NO;
[window_ addSubview:label];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
window_ = nil;
});
//更新徽章数
NSInteger badge = [UIApplication sharedApplication].applicationIconBadgeNumber;
badge --;
badge = badge >= 0? badge :0;
[UIApplication sharedApplication].applicationIconBadgeNumber = badge;
[ZHMeViewController cancelLocalNotifitionWithKey:@"key"];
}