iOS开发中虽然本地推送用的没有远程推送多,但本地推送还是有一定的用武之地,下面简单介绍下实现本地推送的步骤。
第一步:在appDelegate中注册本地推送
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[application registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound categories:nil]];
}
第二步:实现一个推送消息
-(void)localPush{
//这里用gcd创建一个异步的消息推送
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
UILocalNotification *notification = [[UILocalNotification alloc] init];
//5秒后推送消息
NSDate * pushDate = [NSDate dateWithTimeIntervalSinceNow:5];
if (notification != nil) {
//设置推送消息的具体内容,包括时间,主题内容,是否重复,以及应用图标的角标
notification.fireDate = pushDate;
notification.timeZone = [NSTimeZone defaultTimeZone];
notification.repeatInterval = kCFCalendarUnitDay;
notification.soundName = UILocalNotificationDefaultSoundName;
notification.alertBody = @"hello,world";
notification.applicationIconBadgeNumber += 1 ;
//这个字典主要是方便解除本地推送
NSDictionary*info = [NSDictionary dictionaryWithObject:@"test" forKey:@"name"];
notification.userInfo = info;
[[UIApplication sharedApplication] scheduleLocalNotification:notification];
}
});
}
第三步:appDelegate中接收消息
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification{
NSLog(@"%@",notification.alertBody);
//减少角标的显示个数
application.applicationIconBadgeNumber -= 1;;
}
如何解除本地通知
// 首先拿到UIApplication
UIApplication *app = [UIApplication sharedApplication];
//获取本地推送数组
NSArray *localArray = [app scheduledLocalNotifications];
//声明本地通知对象
UILocalNotification *localNotification;
if (localArray) {
for (UILocalNotification *notification in localArray) {
NSDictionary *dict = notification.userInfo;
if (dict) {
NSString *inKey = [dict objectForKey:@"key"];
//这里是根据前面设置的key的名字
if ([inKey isEqualToString:@"name"]) {
if (localNotification){
localNotification = nil;
}
localNotification = notification;
break;
}
}
}
//判断是否找到已经存在的相同key的推送
if (!localNotification) {
//不存在初始化
localNotification = [[UILocalNotification alloc] init];
}
if (localNotification) {
//取消推送
[app cancelLocalNotification:localNotification];
return;
}
}