IOS本地通知(UILocalNotification)的基本使用

直接上代码

ViewController.m

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    
    [self registLocalNotification];
}

- (void)registLocalNotification
{
    UILocalNotification *notification = [[UILocalNotification alloc]init];
    
    notification.fireDate           = [NSDate dateWithTimeIntervalSinceNow:10];
    notification.alertBody          = @"alertBody";
    notification.alertLaunchImage   = @"icon.png";
    
    //如果通知提醒样式为横幅则alertAction属性无显示 样式为提醒的时候alertAction显示为UIAlertView的右侧按钮
    notification.alertAction        = @"alertAction";
    
    notification.soundName          = UILocalNotificationDefaultSoundName;
    notification.timeZone           = [NSTimeZone defaultTimeZone];
    
    //0表示不重复,这里可以设置成每天,每小时等等
    notification.repeatInterval     = 0;
    
    //userInfo用来存储一些信息,比如用于区别其他通知的id等等
    notification.userInfo           = [NSDictionary dictionaryWithObjectsAndKeys:@"tag", @"id",nil];
    notification.applicationIconBadgeNumber = 1;
    
    //生效时间根据fireDate确定
    [[UIApplication sharedApplication] scheduleLocalNotification:notification];
    //立即生效的通知,与fireDate无关
    //[[UIApplication sharedApplication] presentLocalNotificationNow:notification];
    
    //取消通知可以用下面的方法
    //[[UIApplication sharedApplication] cancelLocalNotification:notification];
    //取消全部到本地通知
    //[[UIApplication sharedApplication] cancelAllLocalNotifications];
    
    //通过userInfo来区分不同的通知
    /*
    for (UILocalNotification *notification in [[UIApplication sharedApplication] scheduledLocalNotifications]) {
        NSString *indentiString = [notification.userInfo objectForKey:@"id"];
        if ([indentiString isEqualToString:@"tag"] == YES) {
            [[UIApplication sharedApplication] cancelLocalNotification:notification];
        }
    }
     */
}

@end

在appDelegate.m中实现 通过在通知上的操作进入到程序的监听

/**
 *  如果接受通知的时候应用程序在前台运行,会触发此方法,不会出现声音,提示等信息
 *  如果程序在后台,通过点击通知进入到应用程序也会触发此方法
 *
 *  @param application  当前的应用程序
 *  @param notification 收到的通知
 */
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
    NSLog(@"notification.userInfo=%@",notification.userInfo);
    [application setApplicationIconBadgeNumber:0];
}

通知样式的区别

下图通知样式为横幅


下图通知样式为 提醒

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值