极光&阿里云推送

  • 导入头文件
// 引入JPush功能所需头文件
#import "JPUSHService.h"
// iOS10注册APNs所需头文件
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif
复制代码
  • - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions里写上
JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        // 能够添加自定义categories
        // NSSet<UNNotificationCategory *> *categories for iOS10 or later
        // NSSet<UIUserNotificationCategory *> *categories for iOS8 and iOS9
    }
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    [JPUSHService setupWithOption:launchOptions appKey:PushAppKey
                          channel:@"App Store"
                 apsForProduction:1
            advertisingIdentifier:nil];
复制代码
  • 代理方法
#pragma mark- JPUSHRegisterDelegate
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    /// Required - 注册 DeviceToken
    [JPUSHService registerDeviceToken:deviceToken];
}
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    //Optional
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}

// iOS 12 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center openSettingsForNotification:(UNNotification *)notification API_AVAILABLE(ios(10.0)){
    NSDictionary * userInfo = notification.request.content.userInfo;
    [self getJHMScanResult:userInfo];
    if(@available(iOS 12.1, *)){
        
    }
    if (notification && [notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        //从通知界面直接进入应用
    }else{
        //从通知设置界面进入应用
    }
}
// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler  API_AVAILABLE(ios(10.0)){
    // Required
    NSDictionary * userInfo = notification.request.content.userInfo;
    [self getJHMScanResult:userInfo];
    if(@available(iOS 12.1, *)){
        
    }
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler(UNNotificationPresentationOptionAlert); // 须要执行这个方法,选择是否提醒用户,有 Badge、Sound、Alert 三种类型能够选择设置
}

// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler  API_AVAILABLE(ios(10.0)){
    // Required
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    [self getJHMScanResult:userInfo];
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler();  // 系统要求执行这个方法
}
复制代码
  • 配上程序进入前台就取消角标
- (void)applicationDidBecomeActive:(UIApplication *)application{
    application.applicationIconBadgeNumber = 0;
}
复制代码
  • 在登陆成功后保存别名
[JPUSHService setAlias:[def objectForKey:@"employeesusername"] completion:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {
                        
                    } seq:1];
复制代码
  • 登出后删除别名
//注销推送
-(void)unRegistPush{
    [JPUSHService deleteAlias:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {
        //        if (iResCode == 0)NSLog(@"删除别名成功");
    } seq:1];
}
复制代码

阿里云

  • 导入头文件
#import <CloudPushSDK/CloudPushSDK.h>
// iOS10注册APNs所需头文件
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif
#import <EBBannerView/EBBannerView.h>//这是前台推送第三方
复制代码
  • 注册APNS
- (void)registerAPNS:(UIApplication *)application {
    [application registerUserNotificationSettings: [UIUserNotificationSettings settingsForTypes: (UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];
    [application registerForRemoteNotifications];
}
//APNs注册成功回调,将返回的deviceToken上传到CloudPush服务器
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken NS_AVAILABLE_IOS(3_0) {
    [CloudPushSDK registerDevice:deviceToken withCallback:^(CloudPushCallbackResult *res) {
        if (res.success) {
            VLog(@"\n ====== 注册 deviceToken 成功, deviceToken: %@", [CloudPushSDK getApnsDeviceToken]);
        } else {
            VLog(@"\n ====== 注册 deviceToken 失败, error: %@", res.error);
        }
    }];
}
//APNs注册失败回调
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    VLog(@"\n ====== didFailToRegisterForRemoteNotificationsWithError %@", error);
}
//主动获取设备通知是否受权 (iOS 10+) 能够单独调用(可注释)
- (void)getNotificationSettingStatus {
    if (@available(iOS 10.0, *)) {
        [_notificationCenter getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
            if (settings.authorizationStatus == UNAuthorizationStatusAuthorized) {
                VLog(@"\n ====== User authed.");
            } else {
                VLog(@"\n ====== User denied.");
            }
        }];
    }
}
复制代码
  • 初始化SDK
- (void)initCloudPush {// SDK初始化
    [CloudPushSDK asyncInit:PushAppKey appSecret:PushAppSecret callback:^(CloudPushCallbackResult *res) {
        if (res.success) {
            VLog(@"\n ====== 阿里云推送初始化成功, deviceId: %@.", [CloudPushSDK getDeviceId]);
        } else {
            VLog(@"\n ====== 阿里云推送初始化失败, error: %@", res.error);
        }
    }];
}
复制代码
  • 监听推送消息到达
- (void)registerMessageReceive {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onMessageReceived:) name:@"CCPDidReceiveMessageNotification" object:nil];
}

复制代码
  • 处理到来的消息
//处理到来推送消息
- (void)onMessageReceived:(NSNotification *)notification {
    CCPSysMessage *message = [notification object];
    NSString *title = [[NSString alloc] initWithData:message.title encoding:NSUTF8StringEncoding];
    NSString *body = [[NSString alloc] initWithData:message.body encoding:NSUTF8StringEncoding];
    VLog(@"\n ====== 收到消息 标题: %@, 内容: %@.", title, body);
    VLog(@"\n ====== 当前线程 %@",[NSThread currentThread]);
}
// iOS 7+ 不管是前台仍是后台只要有远程推送都会调用
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler  NS_AVAILABLE_IOS(7_0) {
    if (application.applicationState == UIApplicationStateActive) {// 作相应的判断是前台仍是后台
//    前台默认不展现推送通知和弹窗,因此用了第三方 https://github.com/pikacode/EBBannerView
        [self getJHMScanResult:userInfo];//这个格式跟以前的极光貌似不同,到时候聚合码反扫要试试看
        NSString * content = userInfo[@"aps"][@"alert"][@"body"];
        EBBannerView *banner = [EBBannerView bannerWithBlock:^(EBBannerViewMaker *make) {
            make.style = EBBannerViewStyleiOS11;//custom system, default is current
            make.content = content;
        }];
        [banner show];
    }
}
复制代码
  • 点击通知将 App 从关闭状态启动时,将通知打开回执上报
// 计算点击 OpenCount
[CloudPushSDK sendNotificationAck:launchOptions];
复制代码
  • 程序进入前台清除角标
- (void)applicationDidBecomeActive:(UIApplication *)application{
    application.applicationIconBadgeNumber = 0;
}
复制代码
  • 登陆注册别名(阿里云叫帐号)
[CloudPushSDK bindAccount:[def objectForKey:@"employeesusername"] withCallback:^(CloudPushCallbackResult *res) {
                        
}];
复制代码
  • 退出登陆注销别名(帐号)
[CloudPushSDK unbindAccount:^(CloudPushCallbackResult *res) {
        
}];
复制代码
相关文章
相关标签/搜索