1、什么是本地推送?
所谓的本地推送就是app自己给系统推送的一些消息就叫做本地推送。
2、本地推送的基本应用:有设置、取消以及推送后的回调方法
// 注册(设置)本地推送
+ (void)registLocalNotificationWithTime:(NSInteger)time content:(NSString *)content
{
// 初始化本地通知
UILocalNotification *localNotify = [[UILocalNotification alloc] init];
// 设置触发通知的时间
// dateWithTimeIntervalSinceNow从字面上理解,可以解释为从现在开始多少时间后触发通知
NSDate *fireDate = [NSDate dateWithTimeIntervalSinceNow:time];
localNotify.fireDate = fireDate;
// 设置推送的时区
localNotify.timeZone = [NSTimeZone defaultTimeZone];
// 设置重复的时间间隔 (在多少时间间隔内再次推送通知)
localNotify.repeatInterval = kCFCalendarUnitSecond;
// 设置通知的内容
localNotify.alertBody = content;
// app右上角的数字为1,每推送一次,app右上角就+1
// localNotify.applicationIconBadgeNumber += 1;
// 设置被触发时播放的声音
localNotify.soundName = UILocalNotificationDefaultSoundName;
// 通知参数
NSDictionary *userDict = @{@"key": @"本地通知,你会了么?"};
localNotify.userInfo = userDict;
// iOS8以后需要添加这个(registerUserNotificationSettings)注册才能得到授权
if ([[UIApplication sharedApplication] respondsToSelector:@selector(registerUserNotificationSettings:)]) {
UIUserNotificationType type = UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound;
UIUserNotificationSettings *setting = [UIUserNotificationSettings settingsForTypes:type categories:nil];
// 正是在应用中注册通知
[[UIApplication sharedApplication] registerUserNotificationSettings:setting];
}
// 执行通知注册
[[UIApplication sharedApplication] scheduleLocalNotification:localNotify];
}
// 取消本地推送
+ (void)cancelLocalNotificationWithKey:(NSString *)key
{
NSLog(@"我是来取消通知的");
// 获取所有本地通知的数组
NSArray *localNotifications = [UIApplication sharedApplication].scheduledLocalNotifications;
for (UILocalNotification *localNotification in localNotifications) {
NSDictionary *userInfo = localNotification.userInfo;
if (userInfo) {
// 根据设置通知参数时指定的key来获取通知参数
NSLog(@"%@", userInfo);
NSString *info = userInfo[key];
NSLog(@"%@", info);
// 如果找到需要取消的通知,则取消
if (info) {
[[UIApplication sharedApplication] cancelLocalNotification:localNotification];
NSLog(@"取消一个通知");
break;
}
}
}
}
// 本地通知的回调方法(在应用的前台调用)
+ (void)handleLocalNotification:(UILocalNotification *)localNotify
{
// 获取通知所带的数据
NSString *notMess = [localNotify.userInfo objectForKey:@"key"];
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"本地通知(前台)" message:notMess delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
[alertView show];
// 更新显示徽章(右上角)的个数
NSInteger badge = [UIApplication sharedApplication].applicationIconBadgeNumber;
badge--;
badge = badge > 0 ? badge : 0;
[UIApplication sharedApplication].applicationIconBadgeNumber = badge;
}
网友评论