阅读 275

iOS 本地消息通知

本地消息通知的流程

1.注册

通过调用requestAuthorization这个方法,通知中心会向用户发送通知许可请求。用户在弹出的Alert中心点击“同意”按钮,即可完成注册。

2.创建

首先设置信息内容UNMutableNotificationContent和触发机制UNNotificationTrigger;然后用这两个值来创建UNNotificationRequest;最后将request加入当前通知中心UNUserNotificationCenter.current()

3.推送

这一步就是系统或者远程服务器推送通知的过程。伴随着一声清脆的响声(或自定义的声音),通知对应的UI会显示在手机界面中。

4.响应

当用户看到通知后,点击通知后会看到相应的响应选项。UNNotificationActionUNNotificationCategory用于设置响应选项。

实现

AppDelegate.m

#import "AppDelegate.h"
#import <UserNotifications/UserNotifications.h>

@interface AppDelegate () <UNUserNotificationCenterDelegate>

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    //注册本地推送
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    center.delegate = self;
    [center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert | UNAuthorizationOptionBadge | UNAuthorizationOptionSound)
                          completionHandler:^(BOOL granted, NSError * _Nullable error) {
                              
                          }];
    
    //获取当前的通知设置
    [center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
        
    }];
    
    return YES;
}
#pragma mark - <UNUserNotificationCenterDelegate>
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
    completionHandler(UNNotificationPresentationOptionAlert);
}
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler {
    
    NSString *categoryIdentifier = response.notification.request.content.categoryIdentifier;
    
    // UNNotificationCategory
    if ([categoryIdentifier isEqualToString:@"categoryIdentifier"]) {
        // UNNotificationAction、UNTextInputNotificationAction
        if ([response.actionIdentifier isEqualToString:@"cancelAction"]) {
            
        }
    }
    
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    UNNotificationRequest *request = response.notification.request; // 收到推送的请求
    UNNotificationContent *content = request.content; // 收到推送的消息内容
    
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        NSLog(@"iOS10 收到远程通知");
    } else {
        // 本地通知
        NSLog(@"iOS10 收到本地通知");
    }
    
    completionHandler();
}

@end

添加通知

- (void)addLocalNotification
{
    //创建通知
    UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
    content.title = @"通知标题";
    content.subtitle = @"通知副标题";
    content.body = @"通知内容";
    content.badge = @1;//角标数
    content.categoryIdentifier = @"categoryIdentifier";
  
    //声音设置 [UNNotificationSound soundNamed:@"sound.mp3"] 通知文件要放到bundle里面
    UNNotificationSound *sound = [UNNotificationSound defaultSound];
    content.sound = sound;
    
    //添加附件
    //maxinum 10M
    NSString *imageFile = [[NSBundle mainBundle] pathForResource:@"image" ofType:@"png"];
    //maxinum 5M
    NSString *audioFile = [[NSBundle mainBundle] pathForResource:@"sound" ofType:@"mp3"];
    //maxinum 50M
    //NSString *movieFile = [[NSBundle mainBundle] pathForResource:@"movie" ofType:@"mp4"];

    UNNotificationAttachment *imageAttachment = [UNNotificationAttachment attachmentWithIdentifier:@"iamgeAttachment" URL:[NSURL fileURLWithPath:imageFile] options:nil error:nil];
    UNNotificationAttachment *audioAttachment = [UNNotificationAttachment attachmentWithIdentifier:@"audioAttachment" URL:[NSURL fileURLWithPath:audioFile] options:nil error:nil];
    //添加多个只能显示第一个
    content.attachments = @[audioAttachment,imageAttachment];
     
    /** 通知触发机制
     Trigger 设置本地通知触发条件,它一共有以下几种类型:
     UNPushNotificaitonTrigger 推送服务的Trigger,由系统创建
     UNTimeIntervalNotificationTrigger 时间触发器,可以设置多长时间以后触发,是否重复。如果设置重复,重复时长要大于60s
     UNCalendarNotificationTrigger 日期触发器,可以设置某一日期触发
     UNLocationNotificationTrigger 位置触发器,用于到某一范围之后,触发通知。通过CLRegion设定具体范围。
     */
    UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:5 repeats:NO];
    
    //创建UNNotificationRequest通知请求对象
    NSString *requestIdentifier = @"requestIdentifier";
    UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:requestIdentifier content:content trigger:trigger];
    
    //将通知加到通知中心
    [[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
        
    }];    
}

取消通知

// 取消通知
- (void)cancelLocalNotificaitons {
    
    //获取未展示的通知
    [[UNUserNotificationCenter currentNotificationCenter] getPendingNotificationRequestsWithCompletionHandler:^(NSArray<UNNotificationRequest *> * _Nonnull requests) {
        [[UNUserNotificationCenter currentNotificationCenter] removePendingNotificationRequestsWithIdentifiers:@[@"requestIdentifier"]];
    }];
    
    //获取展示过的通知
    [[UNUserNotificationCenter currentNotificationCenter] getDeliveredNotificationsWithCompletionHandler:^(NSArray<UNNotification *> * _Nonnull notifications) {
        [[UNUserNotificationCenter currentNotificationCenter] removeDeliveredNotificationsWithIdentifiers:@[@"requestIdentifier"]];
    }];
    
    //移除所有还未展示的通知
    //[[UNUserNotificationCenter currentNotificationCenter] removeAllDeliveredNotifications];
    //移除所有已经展示过的通知
    //[[UNUserNotificationCenter currentNotificationCenter] removeAllPendingNotificationRequests];
}

作者:gaookey

原文链接:https://www.jianshu.com/p/07a077435e09

文章分类
后端
文章标签
版权声明:本站是系统测试站点,无实际运营。本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 XXXXXXo@163.com 举报,一经查实,本站将立刻删除。
相关推荐