之前公司一直使用的是信鸽推送,感觉信鸽推送不太好使,现在就换成极光推送了。以下是个人对对于这两者的一些总结,对于没有使用过的可以做一个参考。
信鸽推送:首先去腾讯的官网下载信鸽推送最新的官方SDK http://xg.qq.com/xg/ctr_index/download
完成之后查看接入指南,按照步骤进行接入,在自己工程里面做相关的配置
代码里面如下:
#import "AppDelegate.h"
//做如下配置//信鸽推送
#import "XGPush.h"
#import "XGSetting.h"
#import <UserNotifications/UserNotifications.h>
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
引入信鸽推送的东西和通知的注册。。如果想在打开通知消息进入app进行界面的跳转,可以在接收到推送的方法里面做相关的处理:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
[[XGSetting getInstance] enableDebug:YES];
[XGPush startApp:AppId appKey:AppKey];//app在信鸽注册上 AppId 和 AppKey
[XGPush isPushOn:^(BOOL isPushOn) {
AppLog(@"[XGDemo] Push Is %@", isPushOn ? @"ON" : @"OFF");
}];
[self registerAPNS];
[XGPush handleLaunching:launchOptions successCallback:^{
AppLog(@"[XGDemo] Handle launching success");
} errorCallback:^{
AppLog(@"[XGDemo] Handle launching error");
}];
}
#pragma mark - 信鸽推送
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
NSString *deviceTokenStr = [XGPush registerDevice:deviceToken account:nil successCallback:^{
AppLog(@"[XGDemo] register push success");
} errorCallback:^{
AppLog(@"[XGDemo] register push error");
}];
AppLog(@"[XGDemo] device token is %@", deviceTokenStr);
}
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
AppLog(@"[XGDemo] register APNS fail.\n[XGDemo] reason : %@", error);
}
/**
收到通知的回调
@param application UIApplication 实例
@param userInfo 推送时指定的参数
*/
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
AppLog(@"[XGDemo] receive Notification");
[XGPush handleReceiveNotification:userInfo
successCallback:^{
AppLog(@"[XGDemo] Handle receive success");
} errorCallback:^{
AppLog(@"[XGDemo] Handle receive error");
}];
}
/**
收到静默推送的回调
@param application UIApplication 实例
@param userInfo 推送时指定的参数
@param completionHandler 完成回调
*/
//开启APP的时候
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
AppLog(@"[XGDemo] receive slient Notification");
AppLog(@"[XGDemo] userinfo %@", userInfo);
[XGPush handleReceiveNotification:userInfo
successCallback:^{
[[NSNotificationCenter defaultCenter] postNotificationName:@"XXXXX" object:nil];
AppLog(@"[XGDemo] Handle receive success");
} errorCallback:^{
AppLog(@"[XGDemo] Handle receive error");
}];
completionHandler(UIBackgroundFetchResultNewData);
}
// iOS 10 新增 API
// iOS 10 会走新 API, iOS 10 以前会走到老 API
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
// App 用户点击通知的回调
// 无论本地推送还是远程推送都会走这个回调
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)())completionHandler {
AppLog(@"[XGDemo] click notification");
[XGPush handleReceiveNotification:response.notification.request.content.userInfo
successCallback:^{
AppLog(@"[XGDemo] Handle receive success");
} errorCallback:^{
AppLog(@"[XGDemo] Handle receive error");
}];
completionHandler();
}
// App 在前台弹通知需要调用这个接口
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler {
[[NSNotificationCenter defaultCenter] postNotificationName:@"XXXXX" object:nil];
completionHandler(UNNotificationPresentationOptionBadge | UNNotificationPresentationOptionSound | UNNotificationPresentationOptionAlert);
}
#endif
//设备注册:
- (void)registerAPNS {
float sysVer = [[[UIDevice currentDevice] systemVersion] floatValue];
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
if (sysVer >= 10) {
// iOS 10
[self registerPush10];
} else if (sysVer >= 8) {
// iOS 8-9
[self registerPush8to9];
} else {
// before iOS 8
[self registerPushBefore8];
}
#else
if (sysVer < 8) {
// before iOS 8
[self registerPushBefore8];
} else {
// iOS 8-9
[self registerPush8to9];
}
#endif
}
- (void)registerPush10{
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
center.delegate = self;
[center requestAuthorizationWithOptions:UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert completionHandler:^(BOOL granted, NSError * _Nullable error) {
if (granted) {
}
}];
[[UIApplication sharedApplication] registerForRemoteNotifications];
#endif
}
- (void)registerPush8to9{
UIUserNotificationType types = UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert;
UIUserNotificationSettings *mySettings = [UIUserNotificationSettings settingsForTypes:types categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:mySettings];
[[UIApplication sharedApplication] registerForRemoteNotifications];
}
- (void)registerPushBefore8{
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound)];
}
- (void)applicationWillEnterForeground:(UIApplication *)application {//这个方法可以根据自己的需要进行通知的传递
[[NSNotificationCenter defaultCenter] postNotificationName:@"XXXX" object:nil];
[UIApplication sharedApplication].applicationIconBadgeNumber = 0;
}
- (void)applicationDidBecomeActive:(UIApplication *)application {//这个方法可以根据自己的需要进行通知的传递
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
[[NSNotificationCenter defaultCenter] postNotificationName:@"XXXXX" object:nil];
}
//如果你想针对单个账号做推送,可以使用以下方法:
[XGPush setAccount:XXXX successCallback:^{//这个是单个账号注册推送
AppLog(@"[XGDemo] Set account success");
} errorCallback:^{
AppLog(@"[XGDemo] Set account error");
}];
[XGPush delAccount:^{//切换账号的时候记得删除之前账号的推送
AppLog(@"[XGDemo] Del account success");
} errorCallback:^{
AppLog(@"[XGDemo] Del account error");
}];
//极光推送如下:
先在极光的官网上下载极光推送的相关SDK,然后按照iOS的文档进行配置和引入,打开推送和后台通知:
拿到 appKey
代码相关如下:
#import "AppDelegate.h"
//做如下配置:
#import "JPushNotificationExtensionService.h"
#import "JPUSHService.h"
#import <UserNotifications/UserNotifications.h>
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
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];
/**
launchOptions
appKey:极光注册 的Key 值
channel:@"Publish channel";//一般用这个就可以
isProduction FALSE TRUE //区别生产还是测试
如不需要使用IDFA,advertisingIdentifier 可为nil//这个是广告使用的
*/
[JPUSHService setupWithOption:launchOptions appKey:appKey
channel:channel
apsForProduction:isProduction
advertisingIdentifier:nil];
//2.1.9版本新增获取registration id block接口。
[JPUSHService registrationIDCompletionHandler:^(int resCode, NSString *registrationID) {
if(resCode == 0){
NSLog(@"registrationID获取成功:%@",registrationID);
}
else{
NSLog(@"registrationID获取失败,code:%d",resCode);
}
}];
[JPUSHService setBadge:0];//进来之后设置为0
//这个是自定义使用的
NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
[defaultCenter addObserver:self selector:@selector(networkDidReceiveMessage:) name:kJPFNetworkDidReceiveMessageNotification object:nil];
return YES;
}
- (void)networkDidReceiveMessage:(NSNotification *)notification {//这个是自定义使用的
/**
content:获取推送的内容
extras:获取用户自定义参数
customizeField1:根据自定义key获取自定义的value
*/
NSDictionary * userInfo = [notification userInfo];
NSString *content = [userInfo valueForKey:@"content"];
NSDictionary *extras = [userInfo valueForKey:@"extras"];
NSString *customizeField1 = [extras valueForKey:@"customizeField1"]; //服务端传递的Extras附加字段,key是自己定义的
}
- (void)applicationWillResignActive:(UIApplication *)application {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
- (void)applicationDidEnterBackground:(UIApplication *)application {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
[application setApplicationIconBadgeNumber:0];
}
- (void)applicationWillEnterForeground:(UIApplication *)application {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
[application setApplicationIconBadgeNumber:0];
[application cancelAllLocalNotifications];
}
- (void)applicationDidBecomeActive:(UIApplication *)application {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
- (void)applicationWillTerminate:(UIApplication *)application {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
#pragma mark - 激光推送
- (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);
}
#pragma mark- JPUSHRegisterDelegate
// iOS 10 Support 程序运行通知 `来了会走的方法:
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
// Required
NSDictionary * userInfo = notification.request.content.userInfo;
if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
[JPUSHService handleRemoteNotification:userInfo];
NSLog(@"%@",[[userInfo objectForKey:@"aps"] objectForKey:@"alert"]);
}
completionHandler(UNNotificationPresentationOptionAlert); // 需要执行这个方法,选择是否提醒用户,有Badge、Sound、Alert三种类型可以选择设置
}
/**aps
{
alert = "\U98ce\U5439\U9ea6\U6d6a\U4f60\U662f\U4ec0\U4e48";
badge = 1;
sound = default;
}
*/
// iOS 10 Support 程序从后台进入会走的方法:
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
// Required
NSDictionary * userInfo = response.notification.request.content.userInfo;
if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
[JPUSHService handleRemoteNotification:userInfo];
}
completionHandler(UNNotificationPresentationOptionAlert|UNNotificationPresentationOptionBadge); // 系统要求执行这个方法
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
// Required, iOS 7 Support
[JPUSHService handleRemoteNotification:userInfo];
completionHandler(UIBackgroundFetchResultNewData);
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
// Required,For systems with less than or equal to iOS6
[JPUSHService handleRemoteNotification:userInfo];
}
//单个账号推送 可以使用以下方法:根据对应的需要放在合适的位置:
// NSSet *set = [[NSSet alloc] init];
//这个是增加一个推送
// [JPUSHService addTags:[NSSet setWithObject:@"12345678"] completion:^(NSInteger iResCode, NSSet *iTags, NSInteger seq) {
// if (iResCode) {
// NSLog(@"酒极光推送单个注册成功");
// }
// } seq:0];
//这个四覆盖一个推送 实际根据账号来推送的话 使用这个;
[JPUSHService setTags:[NSSet setWithObject:@"123456789"] completion:^(NSInteger iResCode, NSSet *iTags, NSInteger seq) {
if (iResCode) {
NSLog(@"酒极光推送单个注册成功");
}
} seq:0];
//删除一个标签
[JPUSHService deleteTags:[NSSet setWithObject:@"12345678"] completion:^(NSInteger iResCode, NSSet *iTags, NSInteger seq) {
if (iResCode) {
NSLog(@"酒极光推送单个取消单个标签成功");
}
} seq:0];
//
// //清除所有标签
// [JPUSHService cleanTags:^(NSInteger iResCode, NSSet *iTags, NSInteger seq) {
// if (iResCode) {
// NSLog(@"酒极光推送单个清楚所有标签");
// }
// } seq:0];
//来验证目标tag是否已经设置
// [JPUSHService validTag:@"12345678" completion:^(NSInteger iResCode, NSSet *iTags, NSInteger seq, BOOL isBind) {
// if (iResCode) {
// NSLog(@"来验证目标tag是否已经设置");
// }
// } seq:0];