iOS开发之本地推送、接收到推送的方法

我们有时候有需要本地通知的功能

本地推送通知也需要申请推送通知权限,具体步骤可看我的上一篇博客(关于推送权限申请)

1、添加本地推送的方法,需要判断iOS10.0和iOS8.0不同的方法


#import <UserNotifications/UserNotifications.h>


/** 添加本地推送通知*/
+ (void)addLocalNotificationWithTitle:(NSString *)title subTitle:(NSString *)subTitle body:(NSString *)body timeInterval:(long)timeInterval identifier:(NSString *)identifier userInfo:(NSDictionary *)userInfo repeats:(int)repeats
{
    if (title.length == 0 || body.length == 0 || identifier.length == 0) {
        return;
    }
    if (@available(iOS 10.0, *)) {
        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
        // 标题
        if (title.length) {
            content.title = title;
        }
        if (subTitle.length) {
            content.subtitle = subTitle;
        }
        // 内容
        if (body.length) {
            content.body = body;
        }
        if (userInfo != nil) {
            content.userInfo = userInfo;
        }
        // 声音
        // 默认声音
        content.sound = [UNNotificationSound defaultSound];
        // 添加自定义声音
        //content.sound = [UNNotificationSound soundNamed:@"Alert_ActivityGoalAttained_Salient_Haptic.caf"];
        // 角标 (我这里测试的角标无效,暂时没找到原因)
        content.badge = @1;
        // 多少秒后发送,可以将固定的日期转化为时间
        NSTimeInterval time = [[NSDate dateWithTimeIntervalSinceNow:timeInterval] timeIntervalSinceNow];
        UNNotificationTrigger *trigger = nil;
        // repeats,是否重复,如果重复的话时间必须大于60s,要不会报错
        if (repeats > 0 && repeats < 7) {
            NSDate *date = [NSDate dateWithTimeIntervalSinceNow:timeInterval];
            // 定义一个时间字段的旗标,指定将会获取指定年、月、日、时、分、秒的信息
            unsigned unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitWeekday | NSCalendarUnitMinute | NSCalendarUnitSecond;
            NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
            // 获取不同时间字段的信息
            NSDateComponents* comp = [gregorian components:unitFlags fromDate:date];
            NSDateComponents *components = [[NSDateComponents alloc] init];
            components.second = comp.second;
            if (repeats == 6) {
                //每分钟循环
            } else if (repeats == 5) {
                //每小时循环
                components.minute = comp.minute;
            } else if (repeats == 4) {
                //每天循环
                components.minute = comp.minute;
                components.hour = comp.hour;
            } else if (repeats == 3) {
                //每周循环
                components.minute = comp.minute;
                components.hour = comp.hour;
                components.weekday = comp.weekday;
            } else if (repeats == 2) {
                //每月循环
                components.minute = comp.minute;
                components.hour = comp.hour;
                components.day = comp.day;
                components.month = comp.month;
            } else if (repeats == 1) {
                //每年循环
                components.minute = comp.minute;
                components.hour = comp.hour;
                components.day = comp.day;
                components.month = comp.month;
                components.year = comp.year;
            }
            trigger = [UNCalendarNotificationTrigger triggerWithDateMatchingComponents:components repeats:YES];
        } else {
            //不循环
            trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:time repeats:NO];
        }
        // 添加通知的标识符,可以用于移除,更新等操作 identifier
        UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:identifier content:content trigger:trigger];
        [center addNotificationRequest:request withCompletionHandler:^(NSError *_Nullable error) {
            NSLog(@"ECKPushSDK log:添加本地推送成功");
        }];
    } else {
        UILocalNotification *notif = [[UILocalNotification alloc] init];
        // 发出推送的日期
        notif.fireDate = [NSDate dateWithTimeIntervalSinceNow:timeInterval];
        if (title.length > 0) {
            notif.alertTitle = title;
        }
        // 推送的内容
        if (body.length > 0) {
            notif.alertBody = body;
        }
        if (userInfo != nil) {
            NSMutableDictionary *mdict = [NSMutableDictionary dictionaryWithDictionary:userInfo];
            [mdict setObject:identifier forKey:@"identifier"];
            notif.userInfo = mdict;
        } else {
            // 可以添加特定信息
            notif.userInfo = @{@"identifier":identifier};
        }
        // 角标
        notif.applicationIconBadgeNumber = 1;
        // 提示音
        notif.soundName = UILocalNotificationDefaultSoundName;
        // 循环提醒
        if (repeats == 6) {
            //每分钟循环
            notif.repeatInterval = NSCalendarUnitMinute;
        } else if (repeats == 5) {
            //每小时循环
            notif.repeatInterval = NSCalendarUnitHour;
        } else if (repeats == 4) {
            //每天循环
            notif.repeatInterval = NSCalendarUnitDay;
        } else if (repeats == 3) {
            //每周循环
            notif.repeatInterval = NSCalendarUnitWeekday;
        } else if (repeats == 2) {
            //每月循环
            notif.repeatInterval = NSCalendarUnitMonth;
        } else if (repeats == 1) {
            //每年循环
            notif.repeatInterval = NSCalendarUnitYear;
        } else {
            //不循环
        }
        [[UIApplication sharedApplication] scheduleLocalNotification:notif];
    }
}

2、移除本地推送通知的方法

/** 移除某一个指定的通知*/
+ (void)removeNotificationWithIdentifierID:(NSString *)noticeId
{
    if (@available(iOS 10.0, *)) {
        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        [center getPendingNotificationRequestsWithCompletionHandler:^(NSArray<UNNotificationRequest *> * _Nonnull requests) {
            for (UNNotificationRequest *req in requests){
                NSLog(@"ECKPushSDK log: 当前存在的本地通知identifier: %@\n", req.identifier);
            }
        }];
        [center removePendingNotificationRequestsWithIdentifiers:@[noticeId]];
    } else {
        NSArray *array = [[UIApplication sharedApplication] scheduledLocalNotifications];
        for (UILocalNotification *localNotification in array){
            NSDictionary *userInfo = localNotification.userInfo;
            NSString *obj = [userInfo objectForKey:@"identifier"];
            if ([obj isEqualToString:noticeId]) {
                [[UIApplication sharedApplication] cancelLocalNotification:localNotification];
            }
        }
    }
}

/** 移除所有通知*/
+ (void)removeAllNotification
{
    if (@available(iOS 10.0, *)) {
        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        [center removeAllPendingNotificationRequests];
    }else {
        [[UIApplication sharedApplication] cancelAllLocalNotifications];
    }
}

3、接收到通知处理

iOS10.0之前的接收方法,在Appdelegate中重写下面方法

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
    //接收到本地通知方法
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    //接收到远程通知方法
}

iOS10.0以后的接收推送方法

#import <UserNotifications/UserNotifications.h>

//首先需要设置代理UNUserNotificationCenterDelegate
if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0){
        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        center.delegate = self;
        [center removeAllPendingNotificationRequests];
    }

//再实现UNUserNotificationCenterDelegate代理的方法
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler
{
    //应用在前台时候接收到本地推送通知、远程推送通知调用此方法
}

- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)(void))completionHandler
{
    //应用程序在后台,用户通过点击本地推送、远程推送进入app时调用此方法
}

希望和大家多多交流哈,有不同意见和更好的方法欢迎大家留言相互学习、相互进步。

原文地址:https://www.cnblogs.com/hecanlin/p/10898981.html

时间: 2024-08-01 00:31:33

iOS开发之本地推送、接收到推送的方法的相关文章

iOS开发中通知(Notification)快速入门及推送通知实现教程

iOS开发中通知(Notification)快速入门及推送通知实现教程 标签: NSNotificationCenterNSNotification 2016-11-14 00:18 232人阅读 评论(0) 收藏 举报  分类: iOS(400)  转载自:http://www.111cn.NET/sj/ios8/90190.htm 通知(Notification)是开发框架中观察者模式的一种实现方式,内部的实现机制由Cocoa框架支持,通常用于试图控制器和数据模型的交互.通过通知,可以向一个

C#微信公众号开发系列教程五(接收事件推送与消息排重)

微信公众号开发系列教程一(调试环境部署) 微信公众号开发系列教程一(调试环境部署续:vs远程调试) C#微信公众号开发系列教程二(新手接入指南) C#微信公众号开发系列教程三(消息体签名及加解密) C#微信公众号开发系列教程四(接收普通消息) C#微信公众号开发系列教程五(接收事件推送与消息排重) 在上一篇的博文中讲到,微信的消息可以大体分为两种类型,一种是包括:文本,语音,图片等的普通消息,另一种就是本篇要将的事件类型.包括:关注/取消关注事件,扫描带参数二维码事件,上报地理位置事件,自定义菜

iOS开发之常用第三方框架(下载地址,使用方法,总结)

iOS开发之常用第三方框架(下载地址,使用方法,总结) 说句实话,自学了这么久iOS,如果说我不知道的但是又基本上都摸遍了iOS相关知识,但是每次做项目的时候,遇到难一点的地方或者没试过的东西就闷了. 比如这次,打算做一个着手做一个iOS的项目,是一个关于日计划的小软件,界面都其他的都算满意,网络就不说了,没有服务器,所以很多数据相关的功能不无法实现. 但是嘴头疼的事情就是,比如遇到一个功能的时候,其实如果说要实现的话还是可以的,但是每次在我实现之后我总会想到,这么实现更好,这么实现更简单,更加

ios 开发之本地推送

网络推送可能被人最为重视,但是本地推送有时候项目中也会运用到: 闲话少叙,代码如下: 1.添加根视图 self.window.rootViewController = [[UINavigationController alloc]initWithRootViewController:[[ViewController alloc]init]]; self.window.backgroundColor = [UIColor whiteColor]; [self.window makeKeyAndVi

IOS开发证书变成“此证书的签发者无效”解决方法

转载自:http://blog.csdn.net/h1101723183/article/details/50667325 IOS开发证书全部变成无效,如下图  打包提示错误  解决方法: 1. 下载https://developer.apple.com/certificationauthority/AppleWWDRCA.cer的证书,然后双击安装. 2. 在导航栏那边,显示-显示已过期的证书  3. 点击 “登录”,并且选择 “所有项目” ,并在搜索栏下输入 apple w,其中有一个是无效

iOS开发-播放本地音频(可后台播放)

//初始化音乐 //创建音乐文件路径 NSString *musicFilePath = [[NSBundle mainBundle] pathForResource:@"eyeExe" ofType:@"mp3"]; //判断文件是否存在 if ([[NSFileManager defaultManager] fileExistsAtPath:musicFilePath]) { NSURL *musicURL = [NSURL fileURLWithPath:mu

iOS开发:本地数据存储-NSUserDefaults

Getting Default Values arrayForKey(_:) boolForKey(_:) dataForKey(_:) dictionaryForKey(_:) floatForKey(_:) integerForKey(_:) objectForKey(_:) stringArrayForKey(_:) stringForKey(_:) doubleForKey(_:) URLForKey(_:) Setting Default Values setBool(_:forKey

iOS开发——点击UITextField弹出UIDatePicker的协议实现方法

UITextField是用来接受用户输入的控件,它的优点是灵活性大,用户可以随便输入,但有时候这也是其缺点.对我们而言,典型的一个问题就是格式检查.然而我们也会遇到想让用户输入日期的时候,这个时候再进行格式检查就有些小题大做了,毕竟iOS已经为我们提供了一个UIDatePicker来进行日期选择,这样一个很自然的想法就是当用户点击UITextField的时候弹出的不是键盘,而是我们的UIDatePicker. 一个简单地方法是将自己的UIDatePicker直接赋给UITextField的inp

ios 开发日记 9 - 一些 UIView 中管理 Subview 常用的方法

一些 UIView 中管理 Subview 常用的方法 (2013-01-22 10:04:40) 标签: ios subview it 分类: 關于IOS學習 一些 UIView 中管理 Subview 常用的方法 一个 UIView 里面可以包含许多的 Subview(其他的 UIView),而这些 Subview 彼此之间是有所谓的阶层关系,这有点类似绘图软体中图层的概念,下面程式码示演示了几个在管理图层(Subview)上常用的方法,其程式码如下. 首先是大家最常使用的新增和移除 Sub