极光推送集成

极光推送集成

前言

APP中集成推送的功能是十分常见的,由于移动端的操作系统不同,为了开发的统一与便利,我们都会选择第三方的推送服务。下面就介绍下国内主流的推送平台极光

步骤

应用中集成极光

  • 登录相关的Apple ID(开发者账号)

  • 在工程的capabilities,打开允许推送,如图

  • AppDelegate.m设置相关代码

首先引入头文件

// 引入JPush功能所需头文件
#import <JPUSHService.h>
// iOS10注册APNs所需头文件
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif

如果需要监听自定义消息,需要实现协议JPUSHRegisterDelegate

-didFinishLaunchingWithOptions方法中,配置极光,我们可以把相关代码都列出来

#pragma mark - JPush

- (void)requireNoticePermission {

// iOS8 下需要使用新的 API
if (@available(iOS 10.0, *)) {

UIUserNotificationType myTypes = UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert;
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:myTypes categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
} else if (@available(iOS 8.0, *)) {

UIUserNotificationType myTypes = UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert;
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:myTypes categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
} else {
//        UIRemoteNotificationType myTypes = UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound;
//        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:myTypes];
}

[UIApplication sharedApplication].applicationIconBadgeNumber = 0;
}

- (void)initJPushWithOptions:(NSDictionary *)launchOptions {

[UIApplication sharedApplication].applicationIconBadgeNumber = 0;
[JPUSHService setBadge:0];

[self requireNoticePermission];

NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
[defaultCenter addObserver:self selector:@selector(networkDidReceiveMessage:) name:kJPFNetworkDidReceiveMessageNotification object:nil];

// 3.0.0及以后版本注册可以这样写,也可以继续用旧的注册方式
JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
// 可以添加自定义categories
//        if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0) {
//          NSSet<UNNotificationCategory *> *categories;
//          entity.categories = categories;
//        }
//        else {
//          NSSet<UIUserNotificationCategory *> *categories;
//          entity.categories = categories;
//        }
}
[JPUSHService registerForRemoteNotificationConfig:entity delegate:self];

// 如不需要使用IDFA,advertisingIdentifier 可为nil
NSString *JPushAPIKey = @"93fa800ff6184282e2f33d43";
NSString *JPushChannel = @"App Store";
BOOL JPushProduction = NO;
[JPUSHService setupWithOption:launchOptions appKey:JPushAPIKey
channel:JPushChannel
apsForProduction:JPushProduction
advertisingIdentifier:nil];

//2.1.9版本新增获取registration id block接口。
// [JPUSHService registrationID]
[JPUSHService registrationIDCompletionHandler:^(int resCode, NSString *registrationID) {
if(resCode == 0) {

NSLog(@"registrationID获取成功:%@",registrationID);
}
else{
NSLog(@"registrationID获取失败,code:%d",resCode);
}
}];
}

// 极光推送-自定义消息
- (void)networkDidReceiveMessage:(NSNotification *)notification {

//    NSDictionary *userInfo = [notification userInfo];

//    NSDictionary *extras = [userInfo valueForKey:@"extras"];
//    NSString *customizeField1 = [extras valueForKey:@"customizeField1"]; //服务端传递的Extras附加字段,key是自己定义的
}

- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {

NSLog(@"deviceToken----%@", [NSString stringWithFormat:@"Device Token: %@", deviceToken]);

[JPUSHService registerDeviceToken:deviceToken];
}

- (void)application:(UIApplication *)application
didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}

- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:
(void (^)(UIBackgroundFetchResult))completionHandler {

[JPUSHService handleRemoteNotification:userInfo];

NSLog(@"iOS7及以上系统,收到通知");

if ([[UIDevice currentDevice].systemVersion floatValue] < 10.0 || application.applicationState > 0) {

NSString *title = userInfo[@"aps"][@"alert"];
if (title.length > 0) {

// iOS 10以下,处于前台,展示title
}

}

completionHandler(UIBackgroundFetchResultNewData);
}

#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#pragma mark- JPUSHRegisterDelegate

- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {

NSDictionary * userInfo = notification.request.content.userInfo;

UNNotificationRequest *request = notification.request; // 收到推送的请求
UNNotificationContent *content = request.content; // 收到推送的消息内容

NSNumber *badge = content.badge;  // 推送消息的角标
NSString *body = content.body;    // 推送消息体
UNNotificationSound *sound = content.sound;  // 推送消息的声音
NSString *subtitle = content.subtitle;  // 推送消息的副标题
NSString *title = content.title;  // 推送消息的标题

if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
[JPUSHService handleRemoteNotification:userInfo];

NSString *sound = userInfo[@"aps"][@"sound"];
if (userInfo[@"soundtype"]) {
NSString *soundtype = userInfo[@"soundtype"];
if (soundtype.length) {
sound = soundtype;
}
}

// 声音、震动处理

}
else {
// 判断为本地通知
NSLog(@"iOS10 前台收到本地通知:{\nbody:%@,\ntitle:%@,\nsubtitle:%@,\nbadge:%@,\nsound:%@,\nuserInfo:%@\n}",body,title,subtitle,badge,sound,userInfo);
}
completionHandler(UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionSound|UNNotificationPresentationOptionAlert); // 需要执行这个方法,选择是否提醒用户,有Badge、Sound、Alert三种类型可以设置
}

- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {

// ios 10 收到推送的时候
NSDictionary * userInfo = response.notification.request.content.userInfo;
UNNotificationRequest *request = response.notification.request; // 收到推送的请求
UNNotificationContent *content = request.content; // 收到推送的消息内容

NSNumber *badge = content.badge;  // 推送消息的角标
NSString *body = content.body;    // 推送消息体
UNNotificationSound *sound = content.sound;  // 推送消息的声音
NSString *subtitle = content.subtitle;  // 推送消息的副标题
NSString *title = content.title;  // 推送消息的标题

if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
[JPUSHService handleRemoteNotification:userInfo];
}
else {
// 判断为本地通知
NSLog(@"iOS10 收到本地通知:{\nbody:%@,\ntitle:%@,\nsubtitle:%@,\nbadge:%@,\nsound:%@,\nuserInfo:%@\n}",body,title,subtitle,badge,sound,userInfo);
}

completionHandler();  // 系统要求执行这个方法
}
#endif

最后

如果对大家有帮助,请github上follow和star,本文发布在戴超的技术博客,转载请注明出处

Loading Disqus comments...
Table of Contents