本地通知无需网络,也不需要经过苹果的APNS服务,一般用来进行对用户的定时提醒、备忘录提醒或是游戏里常见的体力满额提醒。不多BB,直接进入正题。
//导入所需要的头文件
#import <UIKit/UILocalNotification.h>
//创先一个本地通知对象
UILocalNotification *notification = [[UILocalNotification alloc] init];
//设置本地通知的触发时间(根据自己实际需求而定),这里我设置了延迟5秒之后发送
notification.fireDate = [NSDate dateWithTimeIntervalSinceNow:5];
//设置是否自定义锁屏时显示的话术(defaults to YES)
notification.hasAction = NO;
//设置通知的文体内容
notification.alertBody = @"本地通知";
//设置锁屏时通知栏里的 滑动来(),这里受hasAction影响,设为YES则显示自己定义的,NO的话则显示默认的‘滑动来查看’
notification.alertAction = @"打开";
//设置通知的标题
notification.alertTitle = @"标题";
//设置通知所用的时区
notification.timeZone = [NSTimeZone defaultTimeZone];
//设置通知的提示音,可自定义或者用系统默认(自定的声音文件要放在工程的mainBundle里,不然会找不到)
notification.soundName = @"in.caf";//这是自定义的
notification.soundName = UILocalNotificationDefaultSoundName//这是使用系统自带
//设置通知的角标
notification.applicationIconBadgeNumber = 2;
//最后发送通知
[[UIApplication sharedApplication] scheduleLocalNotification:notification];
实现的代码写完之后还要在
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
方法里进行配置所需要的通知样式
//UIUserNotificationTypeAlert 弹出框
//UIUserNotificationTypeBadge 角标
//UIUserNotificationTypeSound 提示音
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound categories:nil];
[application registerUserNotificationSettings:settings];
在回调方法里实现你所需要的功能
-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
NSLog(@"接收到本地通知");
}
这个方法的触发条件是:
1、app在前台运行时,
2、点击了通知,把app从后台唤醒时。
(app在后台时,这个方法是不会调用的)
这是iOS10之前的写法,之后会再写一篇关于iOS10本地通知的文章。