许多集成的步骤个推官网都有了,这里只写关于推送的远程推送和本地通知的步骤和代码。APP在后台时:走苹果的APNS通知APP在前台或运行时:做本地通知进行推送AppDelegate.h1.先导入头文件#import "GeTuiSdk.h"2.宏定义#define kGtAppId @""#define kGtAppKey @""#define kGtAppSecret @""3.添加代理@interface AppDelegate : UIResponderAppDelegate.m//个推推送1.宏定义#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0#import#endif2.添加代理@interface AppDelegate ()AppDelegate代理中
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
//注册本地通知
[self registLocationNotification];
//个推-推送功能
// [ GTSdk ]:是否允许APP后台运行
// [GeTuiSdk runBackgroundEnable:YES];
// [ GTSdk ]:是否运行电子围栏Lbs功能和是否SDK主动请求用户定位
[GeTuiSdk lbsLocationEnable:YES andUserVerify:YES];
// [ GTSdk ]:自定义渠道
[GeTuiSdk setChannelId:@"GT-Channel"];
// [ GTSdk ]:使用APPID/APPKEY/APPSECRENT创建个推实例
[GeTuiSdk startSdkWithAppId:kGtAppId appKey:kGtAppKey appSecret:kGtAppSecret delegate:self];
// 注册APNs - custom method - 开发者自定义的方法
[self registerRemoteNotification];
return YES;
}
本地通知注册
#pragma mark注册本地通知
-(void)registLocationNotification
{
if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0){
// 使用 UNUserNotificationCenter 来管理通知
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
//监听回调事件
center.delegate = self;
//iOS 10 使用以下方法注册,才能得到授权
[center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert + UNAuthorizationOptionSound)
completionHandler:^(BOOL granted, NSError * _Nullable error) {
// Enable or disable features based on authorization.
}];
//获取当前的通知设置,UNNotificationSettings 是只读对象,不能直接修改,只能通过以下方法获取
[center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
}];
}else if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0&&[[UIDevice currentDevice].systemVersion floatValue] < 10.0){
if ([[UIApplication sharedApplication] respondsToSelector:@selector(registerUserNotificationSettings:)]) {
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge|UIUserNotificationTypeSound|UIUserNotificationTypeAlert categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
}
}
}
注册个推的远程推送
#pragma mark - 用户通知(推送) _自定义方法
/** 注册远程通知 */
- (void)registerRemoteNotification {
/*
警告:Xcode8的需要手动开启“TARGETS -> Capabilities -> Push Notifications”
*/
/*
警告:该方法需要开发者自定义,以下代码根据APP支持的iOS系统不同,代码可以对应修改。
以下为演示代码,注意根据实际需要修改,注意测试支持的iOS系统都能获取到DeviceToken
*/
if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0) {
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0 // Xcode 8编译会调用
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
center.delegate = self;
[center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionCarPlay) completionHandler:^(BOOL granted, NSError *_Nullable error) {
if (!error) {
NSLog(@"request authorization succeeded!");
}
}];
[[UIApplication sharedApplication] registerForRemoteNotifications];
#else // Xcode 7编译会调用
UIUserNotificationType types = (UIUserNotificationTypeAlert | UIUserNotificationTypeSound | UIUserNotificationTypeBadge);
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:types categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
[[UIApplication sharedApplication] registerForRemoteNotifications];
#endif
} else if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
UIUserNotificationType types = (UIUserNotificationTypeAlert | UIUserNotificationTypeSound | UIUserNotificationTypeBadge);
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:types categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
[[UIApplication sharedApplication] registerForRemoteNotifications];
} else {
UIRemoteNotificationType apn_type = (UIRemoteNotificationType)(UIRemoteNotificationTypeAlert |
UIRemoteNotificationTypeSound |
UIRemoteNotificationTypeBadge);
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:apn_type];
}
}
注册APNS成功返回具体的信息
#pragma mark - 远程通知(推送)回调
/** 远程通知注册成功委托 */
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
NSString *token = [[deviceToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
token = [token stringByReplacingOccurrencesOfString:@" " withString:@""];
NSLog(@"\n>>>[DeviceToken Success]:%@\n\n", token);
// [ GTSdk ]:向个推服务器注册deviceToken
[GeTuiSdk registerDeviceToken:token];
}
/** 远程通知注册失败委托 */
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
NSLog(@"\n>>>[DeviceToken Error]:%@\n\n", error.description);
}
收到远程推送,角标加1
#pragma mark - APP运行中接收到通知(推送)处理 - iOS 10以下版本收到推送
/** APP已经接收到“远程”通知(推送) - 透传推送消息 */
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler {
[GeTuiSdk setBadge:[UIApplication sharedApplication].applicationIconBadgeNumber+1];
// [ GTSdk ]:将收到的APNs信息传给个推统计
[GeTuiSdk handleRemoteNotification:userInfo];
// 控制台打印接收APNs信息
NSLog(@"\n>>>[Receive RemoteNotification]:%@\n\n", userInfo);
completionHandler(UIBackgroundFetchResultNewData);
}
#pragma mark - iOS 10中收到推送消息
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
// iOS 10: App在前台获取到通知
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
NSLog(@"willPresentNotification:%@", notification.request.content.userInfo);
// 根据APP需要,判断是否要提示用户Badge、Sound、Alert
completionHandler(UNNotificationPresentationOptionBadge | UNNotificationPresentationOptionSound | UNNotificationPresentationOptionAlert);
completionHandler(UNNotificationPresentationOptionAlert);
}
###收到远程推送打开app时做的跳转页面###
// iOS 10: 点击通知进入App时触发
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
NSLog(@"didReceiveNotification:%@", response.notification.request.content.userInfo);
// [ GTSdk ]:将收到的APNs信息传给个推统计
[GeTuiSdk handleRemoteNotification:response.notification.request.content.userInfo];
//跳转页面
DetailContentVC *detailVC=[DetailContentVC new];
detailVC.titleValue=_webTitle;
detailVC.requestUrl=_webUrl;
detailVC.hidesBottomBarWhenPushed=YES;
self.window.rootViewController.hidesBottomBarWhenPushed=NO;
[((UITabBarController *)self.window.rootViewController).selectedViewController pushViewController:detailVC animated:YES];
completionHandler();
}
#endif
注册远程推送返回来的cid
#pragma mark - GeTuiSdkDelegate
/** SDK启动成功返回cid */
- (void)GeTuiSdkDidRegisterClient:(NSString *)clientId {
// [4-EXT-1]: 个推SDK已注册,返回clientId
NSLog(@"\n>>[GTSdk RegisterClient]:%@\n\n", clientId);
}
/** SDK遇到错误回调 */
- (void)GeTuiSdkDidOccurError:(NSError *)error {
// [EXT]:个推错误报告,集成步骤发生的任何错误都在这里通知,如果集成后,无法正常收到消息,查看这里的通知。
NSLog(@"\n>>[GTSdk error]:%@\n\n", [error localizedDescription]);
}
透传消息都会走这个,这边是接收离线消息的方法,在这里面去做判断去做本地通知还是远程推送,如果是本地通知,则去注册消息,否则不做任何动作
/** SDK收到透传消息回调 */
- (void)GeTuiSdkDidReceivePayloadData:(NSData *)payloadData andTaskId:(NSString *)taskId andMsgId:(NSString *)msgId andOffLine:(BOOL)offLine fromGtAppId:(NSString *)appId {
// [ GTSdk ]:汇报个推自定义事件(反馈透传消息)
[GeTuiSdk sendFeedbackMessage:90001 andTaskId:taskId andMsgId:msgId];
// 数据转换
NSString *payloadMsg = nil;
if (payloadData) {
payloadMsg = [[NSString alloc] initWithBytes:payloadData.bytes length:payloadData.length encoding:NSUTF8StringEncoding];
}
// 控制台打印日志
NSString *msg = [NSString stringWithFormat:@"taskId=%@,messageId:%@,payloadMsg:%@%@", taskId, msgId, payloadMsg, offLine ? @"<离线消息>" : @""];
NSLog(@"\n>>[GTSdk ReceivePayload]:%@\n\n", msg);
NSError *error=nil;
NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:payloadData options:NSJSONReadingMutableContainers error:&error];
NSString *title=[NSString stringWithFormat:@"%@",dic[@"title"]];
NSString *detail=[NSString stringWithFormat:@"%@",dic[@"text"]];
_webTitle=[NSString stringWithFormat:@"%@",dic[@"messageTitle"]];
_webUrl=[NSString stringWithFormat:@"%@",dic[@"messageUrl"]];
// 当app不在前台时,接收到的推送消息offLine值均为YES
// 判断app是否是点击通知栏消息进行唤醒或开启
// 如果是点击icon图标使得app进入前台,则不做操作,并且同一条推送通知,此方法只执行一次
if (!offLine) {// 离线消息已经有苹果的apns推过消息了,避免上线后再次受到消息
if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0){
[self registerNotification:1 andTitle:title andMess:detail];
}else{
[self registerLocalNotificationInOldWay:1 andTitle:title andMess:detail];
}
}
}
在app运行时恢复个推sdk运行
- (void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
/// Background Fetch 恢复SDK 运行
[GeTuiSdk resume];
completionHandler(UIBackgroundFetchResultNewData);
}
/** SDK收到sendMessage消息回调 */
- (void)GeTuiSdkDidSendMessage:(NSString *)messageId result:(int)result {
// 发送上行消息结果反馈
NSString *msg = [NSString stringWithFormat:@"sendmessage=%@,result=%d", messageId, result];
NSLog(@"\n>>[GTSdk DidSendMessage]:%@\n\n", msg);
}
/** SDK运行状态通知 */
- (void)GeTuiSDkDidNotifySdkState:(SdkStatus)aStatus {
// 通知SDK运行状态
NSLog(@"\n>>[GTSdk SdkState]:%u\n\n", aStatus);
}
/** SDK设置推送模式回调 */
- (void)GeTuiSdkDidSetPushMode:(BOOL)isModeOff error:(NSError *)error {
if (error) {
NSLog(@"\n>>[GTSdk SetModeOff Error]:%@\n\n", [error localizedDescription]);
return;
}
NSLog(@"\n>>[GTSdk SetModeOff]:%@\n\n", isModeOff ? @"开启" : @"关闭");
}
在通知栏点击进来的时候做角标的变化
- (void)handlePushMessage:(NSDictionary *)dict notification:(UILocalNotification *)localNotification {
//开始处理从通知栏点击进来的推送消息
if ([UIApplication sharedApplication].applicationIconBadgeNumber != 0) {
if (localNotification) {
//删除相应信息栏
[[UIApplication sharedApplication] cancelLocalNotification:localNotification];
}
//应用的数字角标减1
[UIApplication sharedApplication].applicationIconBadgeNumber -= 1;
}
else {
[[UIApplication sharedApplication] cancelAllLocalNotifications];
[UIApplication sharedApplication].applicationIconBadgeNumber = 0;
}
}
注册本地通知消息
#pragma mark本地推送
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
//使用 UNNotification 本地通知
-(void)registerNotification:(NSInteger )alerTime andTitle:(NSString*)title andMess:(NSString*)mes{
// 使用 UNUserNotificationCenter 来管理通知
UNUserNotificationCenter* center = [UNUserNotificationCenter currentNotificationCenter];
//需创建一个包含待通知内容的 UNMutableNotificationContent 对象,注意不是 UNNotificationContent ,此对象为不可变对象。
UNMutableNotificationContent* content = [[UNMutableNotificationContent alloc] init];
content.title = [NSString localizedUserNotificationStringForKey:title arguments:nil];
content.body = [NSString localizedUserNotificationStringForKey:mes
arguments:nil];
content.sound = [UNNotificationSound defaultSound];
content.userInfo=@{@"webTitle":_webTitle,@"webUrl":_webUrl};
// 在 alertTime 后推送本地推送
UNTimeIntervalNotificationTrigger* trigger = [UNTimeIntervalNotificationTrigger
triggerWithTimeInterval:alerTime repeats:NO];
UNNotificationRequest* request = [UNNotificationRequest requestWithIdentifier:@"FiveSecond"
content:content trigger:trigger];
//添加推送成功后的处理!
[center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
}];
[[UIApplication sharedApplication] setApplicationIconBadgeNumber:[UIApplication sharedApplication].applicationIconBadgeNumber+1];
[GeTuiSdk setBadge:[UIApplication sharedApplication].applicationIconBadgeNumber];
}
#endif
- (void)registerLocalNotificationInOldWay:(NSInteger)alertTime andTitle:(NSString*)title andMess:(NSString*)mes{
UILocalNotification *notification = [[UILocalNotification alloc] init];
// 设置触发通知的时间
NSDate *fireDate = [NSDate dateWithTimeIntervalSinceNow:alertTime];
NSLog(@"fireDate=%@",fireDate);
notification.fireDate = fireDate;
// 时区
notification.timeZone = [NSTimeZone defaultTimeZone];
// 设置重复的间隔-不重复
notification.repeatInterval = kCFCalendarUnitEra;
// 通知内容
notification.alertBody = title;
notification.applicationIconBadgeNumber = 1;
// 通知被触发时播放的声音
notification.soundName = UILocalNotificationDefaultSoundName;
// 通知参数
NSDictionary *userDict = [NSDictionary dictionaryWithObject:mes forKey:@"key"];
notification.userInfo = userDict;
// ios8后,需要添加这个注册,才能得到授权
if ([[UIApplication sharedApplication] respondsToSelector:@selector(registerUserNotificationSettings:)]) {
UIUserNotificationType type = UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound;
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:type
categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
// 通知重复提示的单位,可以是天、周、月
notification.repeatInterval = NSCalendarUnitDay;
} else {
// 通知重复提示的单位,可以是天、周、月
notification.repeatInterval = NSDayCalendarUnit;
}
// 执行通知注册
[[UIApplication sharedApplication] scheduleLocalNotification:notification];
[[UIApplication sharedApplication] setApplicationIconBadgeNumber:[UIApplication sharedApplication].applicationIconBadgeNumber+1];
[GeTuiSdk setBadge:[UIApplication sharedApplication].applicationIconBadgeNumber];
}
在进入前台的时候要将所有app角标清空,同时告诉个推此时角标为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.
[self updateExpriedStatue];
//推送个数大于0
if (application.applicationIconBadgeNumber>0) { //badge number 不为0,说明程序有那个圈圈图标
//这里进行有关处理
[application setApplicationIconBadgeNumber:0]; //将图标清零。
[GeTuiSdk setBadge:0];
}
}
至此,个推的远程推送和本地通知完成。