許多集成的步驟個推官網(wǎng)都有了,這里只寫關(guān)于推送的遠程推送和本地通知的步驟和代碼储笑。
APP在后臺時:走蘋果的APNS通知
APP在前臺或運行時:做本地通知進行推送
AppDelegate.h#####
1.先導(dǎo)入頭文件
#import "GeTuiSdk.h"
2.宏定義
#define kGtAppId @""
#define kGtAppKey @""
#define kGtAppSecret @""
3.添加代理
@interface AppDelegate : UIResponder <UIApplicationDelegate,GeTuiSdkDelegate>
AppDelegate.m#####
//個推推送
1.宏定義
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
#import <UserNotifications/UserNotifications.h>
#endif
2.添加代理
@interface AppDelegate ()<UNUserNotificationCenterDelegate>
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創(chuàng)建個推實例
[GeTuiSdk startSdkWithAppId:kGtAppId appKey:kGtAppKey appSecret:kGtAppSecret delegate:self];
// 注冊APNs - custom method - 開發(fā)者自定義的方法
[self registerRemoteNotification];
return YES;
}
本地通知注冊
#pragma mark注冊本地通知
-(void)registLocationNotification
{
if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0){
// 使用 UNUserNotificationCenter 來管理通知
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
//監(jiān)聽回調(diào)事件
center.delegate = self;
//iOS 10 使用以下方法注冊,才能得到授權(quán)
[center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert + UNAuthorizationOptionSound)
completionHandler:^(BOOL granted, NSError * _Nullable error) {
// Enable or disable features based on authorization.
}];
//獲取當(dāng)前的通知設(shè)置,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”
*/
/*
警告:該方法需要開發(fā)者自定義,以下代碼根據(jù)APP支持的iOS系統(tǒng)不同掠廓,代碼可以對應(yīng)修改。
以下為演示代碼甩恼,注意根據(jù)實際需要修改蟀瞧,注意測試支持的iOS系統(tǒng)都能獲取到DeviceToken
*/
if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0) {
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0 // Xcode 8編譯會調(diào)用
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編譯會調(diào)用
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 - 遠程通知(推送)回調(diào)
/** 遠程通知注冊成功委托 */
- (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 ]:向個推服務(wù)器注冊deviceToken
[GeTuiSdk registerDeviceToken:token];
}
/** 遠程通知注冊失敗委托 */
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
NSLog(@"\n>>>[DeviceToken Error]:%@\n\n", error.description);
}
收到遠程推送沉颂,角標(biāo)加1
#pragma mark - APP運行中接收到通知(推送)處理 - iOS 10以下版本收到推送
/** APP已經(jīng)接收到“遠程”通知(推送) - 透傳推送消息 */
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler {
[GeTuiSdk setBadge:[UIApplication sharedApplication].applicationIconBadgeNumber+1];
// [ GTSdk ]:將收到的APNs信息傳給個推統(tǒng)計
[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);
// 根據(jù)APP需要,判斷是否要提示用戶Badge悦污、Sound铸屉、Alert
completionHandler(UNNotificationPresentationOptionBadge | UNNotificationPresentationOptionSound | UNNotificationPresentationOptionAlert);
completionHandler(UNNotificationPresentationOptionAlert);
}
###收到遠程推送打開app時做的跳轉(zhuǎn)頁面###
// iOS 10: 點擊通知進入App時觸發(fā)
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
NSLog(@"didReceiveNotification:%@", response.notification.request.content.userInfo);
// [ GTSdk ]:將收到的APNs信息傳給個推統(tǒng)計
[GeTuiSdk handleRemoteNotification:response.notification.request.content.userInfo];
//跳轉(zhuǎn)頁面
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遇到錯誤回調(diào) */
- (void)GeTuiSdkDidOccurError:(NSError *)error {
// [EXT]:個推錯誤報告切端,集成步驟發(fā)生的任何錯誤都在這里通知彻坛,如果集成后,無法正常收到消息踏枣,查看這里的通知昌屉。
NSLog(@"\n>>[GTSdk error]:%@\n\n", [error localizedDescription]);
}
透傳消息都會走這個,這邊是接收離線消息的方法茵瀑,在這里面去做判斷去做本地通知還是遠程推送间驮,如果是本地通知,則去注冊消息马昨,否則不做任何動作
/** SDK收到透傳消息回調(diào) */
- (void)GeTuiSdkDidReceivePayloadData:(NSData *)payloadData andTaskId:(NSString *)taskId andMsgId:(NSString *)msgId andOffLine:(BOOL)offLine fromGtAppId:(NSString *)appId {
// [ GTSdk ]:匯報個推自定義事件(反饋透傳消息)
[GeTuiSdk sendFeedbackMessage:90001 andTaskId:taskId andMsgId:msgId];
// 數(shù)據(jù)轉(zhuǎn)換
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"]];
// 當(dāng)app不在前臺時竞帽,接收到的推送消息offLine值均為YES
// 判斷app是否是點擊通知欄消息進行喚醒或開啟
// 如果是點擊icon圖標(biāo)使得app進入前臺,則不做操作鸿捧,并且同一條推送通知屹篓,此方法只執(zhí)行一次
if (!offLine) {// 離線消息已經(jīng)有蘋果的apns推過消息了,避免上線后再次受到消息
if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0){
[self registerNotification:1 andTitle:title andMess:detail];
}else{
[self registerLocalNotificationInOldWay:1 andTitle:title andMess:detail];
}
}
}
在app運行時恢復(fù)個推sdk運行
- (void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
/// Background Fetch 恢復(fù)SDK 運行
[GeTuiSdk resume];
completionHandler(UIBackgroundFetchResultNewData);
}
/** SDK收到sendMessage消息回調(diào) */
- (void)GeTuiSdkDidSendMessage:(NSString *)messageId result:(int)result {
// 發(fā)送上行消息結(jié)果反饋
NSString *msg = [NSString stringWithFormat:@"sendmessage=%@,result=%d", messageId, result];
NSLog(@"\n>>[GTSdk DidSendMessage]:%@\n\n", msg);
}
/** SDK運行狀態(tài)通知 */
- (void)GeTuiSDkDidNotifySdkState:(SdkStatus)aStatus {
// 通知SDK運行狀態(tài)
NSLog(@"\n>>[GTSdk SdkState]:%u\n\n", aStatus);
}
/** SDK設(shè)置推送模式回調(diào) */
- (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 ? @"開啟" : @"關(guān)閉");
}
在通知欄點擊進來的時候做角標(biāo)的變化
- (void)handlePushMessage:(NSDictionary *)dict notification:(UILocalNotification *)localNotification {
//開始處理從通知欄點擊進來的推送消息
if ([UIApplication sharedApplication].applicationIconBadgeNumber != 0) {
if (localNotification) {
//刪除相應(yīng)信息欄
[[UIApplication sharedApplication] cancelLocalNotification:localNotification];
}
//應(yīng)用的數(shù)字角標(biāo)減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];
//需創(chuàng)建一個包含待通知內(nèi)容的 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];
// 設(shè)置觸發(fā)通知的時間
NSDate *fireDate = [NSDate dateWithTimeIntervalSinceNow:alertTime];
NSLog(@"fireDate=%@",fireDate);
notification.fireDate = fireDate;
// 時區(qū)
notification.timeZone = [NSTimeZone defaultTimeZone];
// 設(shè)置重復(fù)的間隔-不重復(fù)
notification.repeatInterval = kCFCalendarUnitEra;
// 通知內(nèi)容
notification.alertBody = title;
notification.applicationIconBadgeNumber = 1;
// 通知被觸發(fā)時播放的聲音
notification.soundName = UILocalNotificationDefaultSoundName;
// 通知參數(shù)
NSDictionary *userDict = [NSDictionary dictionaryWithObject:mes forKey:@"key"];
notification.userInfo = userDict;
// ios8后饥脑,需要添加這個注冊恳邀,才能得到授權(quán)
if ([[UIApplication sharedApplication] respondsToSelector:@selector(registerUserNotificationSettings:)]) {
UIUserNotificationType type = UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound;
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:type
categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
// 通知重復(fù)提示的單位,可以是天灶轰、周谣沸、月
notification.repeatInterval = NSCalendarUnitDay;
} else {
// 通知重復(fù)提示的單位,可以是天笋颤、周乳附、月
notification.repeatInterval = NSDayCalendarUnit;
}
// 執(zhí)行通知注冊
[[UIApplication sharedApplication] scheduleLocalNotification:notification];
[[UIApplication sharedApplication] setApplicationIconBadgeNumber:[UIApplication sharedApplication].applicationIconBadgeNumber+1];
[GeTuiSdk setBadge:[UIApplication sharedApplication].applicationIconBadgeNumber];
}
在進入前臺的時候要將所有app角標(biāo)清空,同時告訴個推此時角標(biāo)為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];
//推送個數(shù)大于0
if (application.applicationIconBadgeNumber>0) { //badge number 不為0伴澄,說明程序有那個圈圈圖標(biāo)
//這里進行有關(guān)處理
[application setApplicationIconBadgeNumber:0]; //將圖標(biāo)清零赋除。
[GeTuiSdk setBadge:0];
}
}