iOS开发中UILocalNotification实现本地通知实现提醒功能

苹果手机开发中的信息提示推送方式,一类是远程服务器推送(APNS)与UILocalNotification本地通知的,下面我来介绍第二种的使用方法。
 
这两天在做一个闹钟提醒功能,用到了本地通知的功能,记录相关知识如下:

1、本地通知的定义和使用:

本地通知是UILocalNotification的实例,主要有三类属性:

scheduled time,时间周期,用来指定iOS系统发送通知的时间和日期;

notification type,通知类型,包括警告信息、动作按钮的标题、应用图标上的badge(数字标记)和播放的声音;

自定义数据,本地通知可以包含一个dictionary类型的本地数据。

对本地通知的数量限制,iOS最多允许最近本地通知数量是64个,超过限制的本地通知将被iOS忽略。

    UILocalNotification *notification=[[UILocalNotification alloc] init];
    notification.fireDate=[NSDate dateWithTimeIntervalSinceNow:10];
    notification.alertBody=@"闹钟响了。";
    notification.alertTitle=@"请打开闹钟";
    notification.repeatInterval=NSCalendarUnitSecond;
   //设置本地通知的时区
    notification.timeZone = [NSTimeZone defaultTimeZone]; notification.applicationIconBadgeNumber
=1; notification.userInfo=@{@"name":@"zhangsanfeng"}; notification.soundName=UILocalNotificationDefaultSoundName; //[[UIApplication sharedApplication]scheduleLocalNotification:notification]; //[[UIApplication sharedApplication]presentLocalNotificationNow:notification];

2、取消本地通知:

        UIApplication *app=[UIApplication sharedApplication];
        NSArray *array=[app scheduledLocalNotifications];
        NSLog(@"%ld",array.count);
        
        for (UILocalNotification * local in array) {
            NSDictionary *dic= local.userInfo;
            if ([dic[@"name"] isEqual:@"zhangsanfeng"]) {
                //删除指定的通知
                [app cancelLocalNotification:local];
            }
        }
        //也可以使用[app cancelAllLocalNotifications]删除所有通知;    

3、本地通知的响应:

如果已经注册了本地通知,当客户端响应通知时:

    a、应用程序在后台的时候,本地通知会给设备送达一个和远程通知一样的提醒,提醒的样式由用户在手机设置中设置

    b、应用程序正在运行中,则设备不会(而是应用程序)收到提醒,但是会走应用程序delegate中的方法:

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
    //如果你想实现程序在后台时候的那种提醒效果,可以在这个方法中添加相关代码(添加个警告视图)
}

需要注意的是,在情况a中,如果用户点击提醒进入应用程序,也会执行收到本地通知的回调方法,这种情况下如果你添加了上面那段代码,则会出现连续出现两次提示,为了解决这个问题,修改代码如下:

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
    //判断应用程序当前的运行状态,如果是激活状态,则进行提醒,否则不提醒
    if (application.applicationState == UIApplicationStateActive) {
        //显示警告内容
    }
}

4、需要注意:What is the difference between presentLocalNotificationNow and scheduleLocalNotification?

There's no difference right here, but using scheduleLocalNotification you can schedule it at whatever time you want, not only in one second. But presentLocalNotificationNow will show one in exactly one second, not in 0.5 or 2.0 in iOS 8, for example.

前提是你的应用程序不处于激活状态,本地通知才会有效果;

你可能感兴趣的:(iOS开发中UILocalNotification实现本地通知实现提醒功能)