您的位置:首页 > 移动开发 > IOS开发

IOS本地通知实现

2016-03-26 21:46 836 查看
当一段时间没有使用一个APP的时候(例如消消乐, 熊猫读书等), 其都会自动的跳出一个通知, 告诉你多久没有用过这个app了,同时提醒你再次使用,目的是为其留住现有的用户.

本地通知,不像远程通知还要请求苹果APNs服务器,其推送消息的过程较为简单,下面探讨下具体的实现原理.

注意:如果苹果设备是ios8系统以上,需要请求通知,在AppDelegate.m的

<span style="font-size:14px;">- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions</span>


这个方法中实现请求通知

<span style="font-size:14px;">//判断当前设备的系统
if ([[UIDevice currentDevice].systemVersion doubleValue] >= 8.0) {
UIUserNotificationType type = UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound;
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:type categories:nil];
// 注册通知类型
[application registerUserNotificationSettings:settings];

[application registerForRemoteNotifications];
}</span>


然后,可以在要实现通知的控制器中,具体实现通知的代码逻辑

第一步:创建本地通知;

第二步:设置本地通知的附带信息;

第三步:注册通知.

其中第二步中,通知的附带信息有

<span style="font-size:14px;">@property(nonatomic,copy) NSDate *fireDate; 指定通知发送的时间
@property(nonatomic,copy) NSTimeZone *timeZone; 指定发送通知的时区
@property(nonatomic) NSCalendarUnit repeatInterval;  重复的周期, 枚举
@property(nonatomic,copy) NSCalendar *repeatCalendar; 重复的周期
@property(nonatomic,copy) NSString *alertBody;      通知内容
@property(nonatomic) BOOL hasAction;                是否需要滑动事件
@property(nonatomic,copy) NSString *alertAction;    锁屏状态的标题
@property(nonatomic,copy) NSString *alertLaunchImage;   点击通知之后的启动图片
@property(nonatomic,copy) NSString *soundName;    收到通知播放的音乐
@property(nonatomic) NSInteger applicationIconBadgeNumber;  图标提醒数字
@property(nonatomic,copy) NSDictionary *userInfo;   额外的信息</span>


可以根据具体的要求,实现相关的信息,具体代码为:

<span style="font-size:14px;"> //1.创建本地通知对象
UILocalNotification *note = [[UILocalNotification alloc] init];

//1.1指定通知发送时间
note.fireDate = [NSDate dateWithTimeIntervalSinceNow:5];

//1.2指定通知内容
note.alertBody = @"本地通知测试";

//1.3锁屏状态的标题
note.alertAction = @"锁屏信息";

//1.4额外的信息
note.userInfo = @{
@"name":@"xiaoming",
@"age":@"24"
};

//2.注册通知
UIApplication *application = [UIApplication sharedApplication];

[application scheduleLocalNotification:note];</span>


当收到通知的信息的时候,系统会执行AppDelegate.m中的代理方法

<span style="font-size:14px;">// 接收到本地通知时就会调用
// 当程序在前台时, 会自动调用该方法
// 当程序 还后台时, 只有用户点击了通知才会调用
//如果应用程序是关闭状态会调用didFinishLaunchingWithOptions
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification{
//获取通知的数据
NSLog(@"%@", notification.userInfo);
}
</span>


当应用程序是关闭状态会调用application:didFinishLaunchingWithOptionS

数据可以从launchOptions中取出
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: