oc 通知

作者: 喵喵粉 | 来源:发表于2021-03-31 18:12 被阅读0次

    版本:
    10.0+
    8.0-10.0
    8.0

    1. AppDelegate.m
    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary<UIApplicationLaunchOptionsKey,id> *)launchOptions {
        
        [self getRemoteNofificationData:launchOptions];
        [self getLocalNofificationData:launchOptions];
        [self registerUserNotification:application];
        [self getNotificationAuthStatus];
        
        return YES;
    }
    
    1. AppDelegate+Notification.h
    @interface AppDelegate (Notification)
    
    ///注册用户通知
    - (void)registerUserNotification:(UIApplication *)application;
    ///添加本地推送
    - (void)addLocalNotification;
    ///移除全部通知
    - (void)cancelAllLocation;
    ///获取推送内容
    - (void)getLocalNofificationData:(NSDictionary<UIApplicationLaunchOptionsKey,id> *)launchOptions;
    - (void)getRemoteNofificationData:(NSDictionary<UIApplicationLaunchOptionsKey,id> *)launchOptions;
    ///获取通知授权状态
    - (void)getNotificationAuthStatus;
    
    @end  
    
    1. AppDelegate+Notification.m
    //  https://www.jb51.net/article/93602.htm
    
    #import "AppDelegate+Notification.h"
    #import <UserNotifications/UserNotifications.h>
    
    @interface AppDelegate (Notification)<UNUserNotificationCenterDelegate>
    
    @end
    
    @implementation AppDelegate (Notification)
    
    ///获取推送内容
    - (void)getRemoteNofificationData:(NSDictionary<UIApplicationLaunchOptionsKey,id> *)launchOptions {
        id notify = launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey];
        notify = launchOptions[UIApplicationDidFinishLaunchingNotification];
        
        NSLog(@"获取推送内容 %@", notify);
    }
    - (void)getLocalNofificationData:(NSDictionary<UIApplicationLaunchOptionsKey,id> *)launchOptions API_AVAILABLE(ios(8.0))  {
        UILocalNotification *notification = launchOptions[UIApplicationLaunchOptionsLocalNotificationKey];
        NSLog(@"获取local推送内容 %@", notification.userInfo);
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"通知" message:notification.userInfo.description preferredStyle:UIAlertControllerStyleAlert];
            [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]];
            [self.window.rootViewController presentViewController:alert animated:YES completion:nil];
        });
    }
    
    ///注册用户通知
    - (void)registerUserNotification:(UIApplication *)application {
        
        if (@available(iOS 10.0, *)) {
            UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
            //必须写代理,不然无法监听通知的接收与点击事件
            center.delegate = self;
            
            //using UNUserNotificationCenter both local and remote notifications.
            [center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert) completionHandler:^(BOOL granted, NSError *error) {
                if (!error && granted) {
                    //用户点击允许
                    NSLog(@"注册成功");
                } else {
                    //用户点击不允许
                    NSLog(@"注册失败");
                }
            }];
            
            // 可以通过 getNotificationSettingsWithCompletionHandler 获取权限设置
            //之前注册推送服务,用户点击了同意还是不同意,以及用户之后又做了怎样的更改我们都无从得知,现在 apple 开放了这个 API,我们可以直接获取到用户的设定信息了。注意UNNotificationSettings是只读对象哦,不能直接修改!
            [center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings *settings) {
                NSLog(@"========%@",settings);
            }];
            
            //注册远端消息通知获取device token
            [application registerForRemoteNotifications];
            
        } else if (@available(iOS 8.0, *)) {
            //iOS 8 - iOS 10系统
            [application registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound categories:nil]];
            
            //注册远端消息通知获取device token
            [application registerForRemoteNotifications];
            
        } else  {
            //iOS 8.0系统以下
            [application registerForRemoteNotificationTypes:UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound];
        }
    }
    
    ///获取通知授权状态
    - (void)getNotificationAuthStatus {
        if (@available(iOS 10.0, *)) {
            UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
            center.delegate = self;
            [center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings *settings) {
                switch (settings.authorizationStatus) {
                    case UNAuthorizationStatusNotDetermined:
                        [center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert) completionHandler:^(BOOL granted, NSError *error) {
                            if (granted) {
                                //注册
                                dispatch_async(dispatch_get_main_queue(), ^{
                                    [UIApplication.sharedApplication registerForRemoteNotifications];
                                });
                            } else {
                                //拒绝❌推送
                            }
                        }];
                        break;
                    case UNAuthorizationStatusDenied:
                        NSLog(@"关闭了通知");
                        break;
                    case UNAuthorizationStatusAuthorized:
                        //注册
    //                    dispatch_async(dispatch_get_main_queue(), ^{
    //                        [UIApplication.sharedApplication registerForRemoteNotifications];
    //                    });
                    case UNAuthorizationStatusProvisional:
                        //注册
    //                    dispatch_async(dispatch_get_main_queue(), ^{
    //                        [UIApplication.sharedApplication registerForRemoteNotifications];
    //                    });
                        break;
                    default:
                        break;
                }
            }];
        } else if (@available(iOS 8.0, *)) {
            UIUserNotificationSettings *settings = UIApplication.sharedApplication.currentUserNotificationSettings;
            BOOL isNotEnable = (settings.types == UIUserNotificationTypeNone);
            if (isNotEnable) {
                [UIApplication.sharedApplication registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound categories:nil]];
            } else {
                [self addLocalNotification];
            }
        } else {
            UIRemoteNotificationType type = UIApplication.sharedApplication.enabledRemoteNotificationTypes;
            BOOL isEnable = (type == UIRemoteNotificationTypeNone);
        }
    }
    
    #pragma mark - locat notification
    
    - (void)addLocalNotification {
        if (@available(iOS 10.0, *)) {
            
            //取消之前的通知
            [self cancelAllLocation];
            
            //推送内容
            UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
            content.title = @"10 title";
            content.body = @"10 body";
            content.sound = UNNotificationSound.defaultSound;
            
            //exception 'NSInternalInconsistencyException', reason: 'time interval must be at least 60 if repeating'
            UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:10 repeats:NO];
            
            //添加本地推送
            UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"a" content:content trigger:trigger];
            //推送成功后
            UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
            [center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"本地通知" message:@"成功添加推送" preferredStyle:UIAlertControllerStyleAlert];
                    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil]];
                    [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alert animated:YES completion:nil];
                });
            }];
            
        } else {
            UILocalNotification *notification = [[UILocalNotification alloc] init];
            notification.fireDate = [NSDate dateWithTimeIntervalSinceNow:2];
            notification.alertBody = @"alertBody";
            notification.alertAction = @"alertAction";
            notification.alertTitle = @"alertTitle";
            
            [UIApplication.sharedApplication scheduleLocalNotification:notification];
        }
    }
    
    ///移除全部通知
    - (void)cancelAllLocation {
        if (@available(iOS 10.0, *)){
            UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
            [center removeAllPendingNotificationRequests];
        } else {
            [[UIApplication sharedApplication] cancelAllLocalNotifications];
        }
    }
    
    ///前台收到消息 后台收到可用在didFinsh中获取
    - (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
    }
    
    #pragma mark - RemoteNotifications
    
    - (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings API_AVAILABLE(ios(8.0)) {
        
    }
    
    - (void)application:(UIApplication*)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
        
        if (@available(iOS 13.0, *)) {
            if (![deviceToken isKindOfClass:[NSData class]])
                return;
            
            const unsigned *tokenBytes = [deviceToken bytes];
            NSString *hexToken = [NSString stringWithFormat:@"%08x%08x%08x%08x%08x%08x%08x%08x",
                                  ntohl(tokenBytes[0]), ntohl(tokenBytes[1]), ntohl(tokenBytes[2]),
                                  ntohl(tokenBytes[3]), ntohl(tokenBytes[4]), ntohl(tokenBytes[5]),
                                  ntohl(tokenBytes[6]), ntohl(tokenBytes[7])];
            
            NSLog(@"deviceToken:%@", hexToken);
        } else {
            
            NSString *deviceTokenStr = [NSString stringWithFormat:@"%@",deviceToken];
            
            deviceTokenStr = [deviceTokenStr stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
            deviceTokenStr = [deviceTokenStr stringByReplacingOccurrencesOfString:@" " withString:@""];
    
            NSLog(@"--------%@", deviceTokenStr);
        }
    }
    
    - (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
        
    }
    
    - (void)application:(UIApplication*)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
        
    }
    
    //iOS 8 接受到推送的处理方法
    - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
        completionHandler(UIBackgroundFetchResultNewData);
    }
    
    #pragma mark - iOS 10 UNUserNotificationCenterDelegate
    
    // The method will be called on the delegate only if the application is in the foreground. If the method is not implemented or the handler is not called in a timely manner then the notification will not be presented. The application can choose to have the notification presented as a sound, badge, alert and/or in the notification list. This decision should be based on whether the information in the notification is otherwise visible to the user.
    - (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler API_AVAILABLE(ios(10.0)) {
        //前台收到消息
        NSDictionary *userInfo = notification.request.content.userInfo;
        NSLog(@"willPresentNotification %@", userInfo);
    
        completionHandler(UNNotificationPresentationOptionBadge | UNNotificationPresentationOptionSound | UNNotificationPresentationOptionAlert);
    }
    
    // The method will be called on the delegate when the user responded to the notification by opening the application, dismissing the notification or choosing a UNNotificationAction. The delegate must be set before the application returns from application:didFinishLaunchingWithOptions:.
    - (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)(void))completionHandler API_AVAILABLE(ios(10.0)) {
        //后台收到消息
        NSDictionary *userInfo = response.notification.request.content.userInfo;
        NSLog(@"didReceiveNotificationResponse %@", userInfo);
    
         completionHandler();
    }
    
    // 从手机设置-通知设置打开app
    //The method will be called on the delegate when the application is launched in response to the user's request to view in-app notification settings. Add UNAuthorizationOptionProvidesAppNotificationSettings as an option in requestAuthorizationWithOptions:completionHandler: to add a button to inline notification settings view and the notification settings view in Settings. The notification will be nil when opened from Settings.
    - (void)userNotificationCenter:(UNUserNotificationCenter *)center openSettingsForNotification:(nullable UNNotification *)notification API_AVAILABLE(ios(12.0)) {
        
    }
    
    @end
    

    2. 通知设置

    通知设置的打印

    
    //正常的
    1 <UNNotificationSettings: 0x2816d2400; authorizationStatus: Authorized, notificationCenterSetting: Enabled, soundSetting: Enabled, badgeSetting: Enabled, lockScreenSetting: Enabled, carPlaySetting: NotSupported, announcementSetting: Disabled, criticalAlertSetting: NotSupported, timeSensitiveSetting: NotSupported, alertSetting: Enabled, scheduledDeliverySetting: Disabled, directMessagesSetting: NotSupported, alertStyle: Banner, groupingSetting: Default providesAppNotificationSettings: Yes>
    //全部关闭
    1 <UNNotificationSettings: 0x2816d32a0; authorizationStatus: Denied, notificationCenterSetting: Disabled, soundSetting: Disabled, badgeSetting: Disabled, lockScreenSetting: Disabled, carPlaySetting: NotSupported, announcementSetting: Disabled, criticalAlertSetting: NotSupported, timeSensitiveSetting: NotSupported, alertSetting: Disabled, scheduledDeliverySetting: Disabled, directMessagesSetting: NotSupported, alertStyle: None, groupingSetting: Default providesAppNotificationSettings: No>
    
    
    //关掉‘通知中心’
    1 <UNNotificationSettings: 0x2816cca20; authorizationStatus: Authorized, notificationCenterSetting: Disabled, soundSetting: Enabled, badgeSetting: Enabled, lockScreenSetting: Enabled, carPlaySetting: NotSupported, announcementSetting: Disabled, criticalAlertSetting: NotSupported, timeSensitiveSetting: NotSupported, alertSetting: Enabled, scheduledDeliverySetting: Disabled, directMessagesSetting: NotSupported, alertStyle: Banner, groupingSetting: Default providesAppNotificationSettings: Yes>
    
    
    //关掉‘横幅’
    1 <UNNotificationSettings: 0x2816d34e0; authorizationStatus: Authorized, notificationCenterSetting: Enabled, soundSetting: Enabled, badgeSetting: Enabled, lockScreenSetting: Enabled, carPlaySetting: NotSupported, announcementSetting: Disabled, criticalAlertSetting: NotSupported, timeSensitiveSetting: NotSupported, alertSetting: Disabled, scheduledDeliverySetting: Disabled, directMessagesSetting: NotSupported, alertStyle: None, groupingSetting: Default providesAppNotificationSettings: Yes>
    
    
    //关掉‘锁屏’
    1 <UNNotificationSettings: 0x2816cd830; authorizationStatus: Authorized, notificationCenterSetting: Enabled, soundSetting: Enabled, badgeSetting: Enabled, lockScreenSetting: Disabled, carPlaySetting: NotSupported, announcementSetting: Disabled, criticalAlertSetting: NotSupported, timeSensitiveSetting: NotSupported, alertSetting: Enabled, scheduledDeliverySetting: Disabled, directMessagesSetting: NotSupported, alertStyle: Banner, groupingSetting: Default providesAppNotificationSettings: Yes>
    
    
    //显示预览 - 解锁时
    1 <UNNotificationSettings: 0x2816ca0a0; authorizationStatus: Authorized, notificationCenterSetting: Enabled, soundSetting: Enabled, badgeSetting: Enabled, lockScreenSetting: Enabled, carPlaySetting: NotSupported, announcementSetting: Disabled, criticalAlertSetting: NotSupported, timeSensitiveSetting: NotSupported, alertSetting: Enabled, scheduledDeliverySetting: Disabled, directMessagesSetting: NotSupported, alertStyle: Banner, groupingSetting: Default providesAppNotificationSettings: Yes>
    //显示预览 - 用不
    1 <UNNotificationSettings: 0x2816ca0a0; authorizationStatus: Authorized, notificationCenterSetting: Enabled, soundSetting: Enabled, badgeSetting: Enabled, lockScreenSetting: Enabled, carPlaySetting: NotSupported, announcementSetting: Disabled, criticalAlertSetting: NotSupported, timeSensitiveSetting: NotSupported, alertSetting: Enabled, scheduledDeliverySetting: Disabled, directMessagesSetting: NotSupported, alertStyle: Banner, groupingSetting: Default providesAppNotificationSettings: Yes>
    
    
    //通知分组 - app
    1 <UNNotificationSettings: 0x2816ca130; authorizationStatus: Authorized, notificationCenterSetting: Enabled, soundSetting: Enabled, badgeSetting: Enabled, lockScreenSetting: Enabled, carPlaySetting: NotSupported, announcementSetting: Disabled, criticalAlertSetting: NotSupported, timeSensitiveSetting: NotSupported, alertSetting: Enabled, scheduledDeliverySetting: Disabled, directMessagesSetting: NotSupported, alertStyle: Banner, groupingSetting: Source providesAppNotificationSettings: Yes>
    //通知分组 - 关
    1 <UNNotificationSettings: 0x2816d3450; authorizationStatus: Authorized, notificationCenterSetting: Enabled, soundSetting: Enabled, badgeSetting: Enabled, lockScreenSetting: Enabled, carPlaySetting: NotSupported, announcementSetting: Disabled, criticalAlertSetting: NotSupported, timeSensitiveSetting: NotSupported, alertSetting: Enabled, scheduledDeliverySetting: Disabled, directMessagesSetting: NotSupported, alertStyle: Banner, groupingSetting: Off providesAppNotificationSettings: Yes>
    

    3. 接入极光SDK

    在设置-app-通知,点击“通知设置”跳到app

    UNUserNotificationCenter的代理

    // The method will be called on the delegate when the application is launched in response to the user's request to view in-app notification settings. Add UNAuthorizationOptionProvidesAppNotificationSettings as an option in requestAuthorizationWithOptions:completionHandler: to add a button to inline notification settings view and the notification settings view in Settings. The notification will be nil when opened from Settings.
    - (void)userNotificationCenter:(UNUserNotificationCenter *)center openSettingsForNotification:(nullable UNNotification *)notification API_AVAILABLE(macos(10.14), ios(12.0)) API_UNAVAILABLE(watchos, tvos);
    
    #pragma mark- JPUSHRegisterDelegate
    
    // iOS 12 Support
    - (void)jpushNotificationCenter:(UNUserNotificationCenter *)center openSettingsForNotification:(UNNotification *)notification {
        NSLog(@"--notify--");
        if (notification && [notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
            //从通知界面直接进入应用
            NSLog(@"从通知界面直接进入应用");
        } else{
            //从通知设置界面进入应用
            NSLog(@"从通知【设置】界面进入应用");
        }
    }
    

    相关文章

      网友评论

          本文标题:oc 通知

          本文链接:https://www.haomeiwen.com/subject/hwdahltx.html