iOS個(gè)推遠(yuǎn)程推送和本地通知

許多集成的步驟個(gè)推官網(wǎng)都有了,這里只寫關(guān)于推送的遠(yuǎn)程推送和本地通知的步驟和代碼。

APP在后臺(tái)時(shí):走蘋果的APNS通知
APP在前臺(tái)或運(yùn)行時(shí):做本地通知進(jìn)行推送

AppDelegate.h#####
1.先導(dǎo)入頭文件
#import "GeTuiSdk.h"
2.宏定義
#define kGtAppId           @""
#define kGtAppKey          @""
#define kGtAppSecret       @""
3.添加代理
@interface AppDelegate : UIResponder <UIApplicationDelegate,GeTuiSdkDelegate>
AppDelegate.m#####
//個(gè)推推送
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.
    //注冊(cè)本地通知
    [self registLocationNotification];
    
    //個(gè)推-推送功能
    // [ GTSdk ]:是否允許APP后臺(tái)運(yùn)行
    //    [GeTuiSdk runBackgroundEnable:YES];
    
    // [ GTSdk ]:是否運(yùn)行電子圍欄Lbs功能和是否SDK主動(dòng)請(qǐng)求用戶定位
    [GeTuiSdk lbsLocationEnable:YES andUserVerify:YES];
    
    // [ GTSdk ]:自定義渠道
    [GeTuiSdk setChannelId:@"GT-Channel"];
    
    // [ GTSdk ]:使用APPID/APPKEY/APPSECRENT創(chuàng)建個(gè)推實(shí)例
    [GeTuiSdk startSdkWithAppId:kGtAppId appKey:kGtAppKey appSecret:kGtAppSecret delegate:self];
    
    // 注冊(cè)APNs - custom method - 開發(fā)者自定義的方法
    [self registerRemoteNotification];
   
    return YES;
}

本地通知注冊(cè)

#pragma mark注冊(cè)本地通知
-(void)registLocationNotification
{
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0){
        // 使用 UNUserNotificationCenter 來管理通知
        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        //監(jiān)聽回調(diào)事件
        center.delegate = self;
        
        //iOS 10 使用以下方法注冊(cè),才能得到授權(quán)
        [center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert + UNAuthorizationOptionSound)
                              completionHandler:^(BOOL granted, NSError * _Nullable error) {
                                  // Enable or disable features based on authorization.
                              }];
        
        //獲取當(dāng)前的通知設(shè)置,UNNotificationSettings 是只讀對(duì)象,不能直接修改,只能通過以下方法獲取
        [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];
        }
    }
}

注冊(cè)個(gè)推的遠(yuǎn)程推送

#pragma mark - 用戶通知(推送) _自定義方法

/** 注冊(cè)遠(yuǎn)程通知 */
- (void)registerRemoteNotification {
    /*
     警告:Xcode8的需要手動(dòng)開啟“TARGETS -> Capabilities -> Push Notifications”
     */
    
    /*
     警告:該方法需要開發(fā)者自定義,以下代碼根據(jù)APP支持的iOS系統(tǒng)不同,代碼可以對(duì)應(yīng)修改。
     以下為演示代碼,注意根據(jù)實(shí)際需要修改,注意測(cè)試支持的iOS系統(tǒng)都能獲取到DeviceToken
     */
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0) {
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0 // Xcode 8編譯會(huì)調(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編譯會(huì)調(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];
    }
}

注冊(cè)APNS成功返回具體的信息

#pragma mark - 遠(yuǎn)程通知(推送)回調(diào)

/** 遠(yuǎn)程通知注冊(cè)成功委托 */
- (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 ]:向個(gè)推服務(wù)器注冊(cè)deviceToken
    [GeTuiSdk registerDeviceToken:token];
}
/** 遠(yuǎn)程通知注冊(cè)失敗委托 */
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    NSLog(@"\n>>>[DeviceToken Error]:%@\n\n", error.description);
}

收到遠(yuǎn)程推送,角標(biāo)加1

#pragma mark - APP運(yùn)行中接收到通知(推送)處理 - iOS 10以下版本收到推送

/** APP已經(jīng)接收到“遠(yuǎn)程”通知(推送) - 透?jìng)魍扑拖? */
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler {
    [GeTuiSdk setBadge:[UIApplication sharedApplication].applicationIconBadgeNumber+1];
    
    // [ GTSdk ]:將收到的APNs信息傳給個(gè)推統(tǒng)計(jì)
    [GeTuiSdk handleRemoteNotification:userInfo];
    
    // 控制臺(tái)打印接收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在前臺(tái)獲取到通知
- (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);
}

###收到遠(yuǎn)程推送打開app時(shí)做的跳轉(zhuǎn)頁(yè)面###
//  iOS 10: 點(diǎn)擊通知進(jìn)入App時(shí)觸發(fā)
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    
    NSLog(@"didReceiveNotification:%@", response.notification.request.content.userInfo);
    
    // [ GTSdk ]:將收到的APNs信息傳給個(gè)推統(tǒng)計(jì)
    [GeTuiSdk handleRemoteNotification:response.notification.request.content.userInfo];
    
    //跳轉(zhuǎn)頁(yè)面
    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

注冊(cè)遠(yuǎn)程推送返回來的cid

#pragma mark - GeTuiSdkDelegate

/** SDK啟動(dòng)成功返回cid */
- (void)GeTuiSdkDidRegisterClient:(NSString *)clientId {
    // [4-EXT-1]: 個(gè)推SDK已注冊(cè),返回clientId
    NSLog(@"\n>>[GTSdk RegisterClient]:%@\n\n", clientId);
}

/** SDK遇到錯(cuò)誤回調(diào) */
- (void)GeTuiSdkDidOccurError:(NSError *)error {
    // [EXT]:個(gè)推錯(cuò)誤報(bào)告,集成步驟發(fā)生的任何錯(cuò)誤都在這里通知,如果集成后,無法正常收到消息,查看這里的通知。
    NSLog(@"\n>>[GTSdk error]:%@\n\n", [error localizedDescription]);
}

透?jìng)飨⒍紩?huì)走這個(gè),這邊是接收離線消息的方法,在這里面去做判斷去做本地通知還是遠(yuǎn)程推送,如果是本地通知,則去注冊(cè)消息,否則不做任何動(dòng)作

/** SDK收到透?jìng)飨⒒卣{(diào) */
- (void)GeTuiSdkDidReceivePayloadData:(NSData *)payloadData andTaskId:(NSString *)taskId andMsgId:(NSString *)msgId andOffLine:(BOOL)offLine fromGtAppId:(NSString *)appId {
    // [ GTSdk ]:匯報(bào)個(gè)推自定義事件(反饋透?jìng)飨?
    [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];
    }
    
    // 控制臺(tái)打印日志
    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不在前臺(tái)時(shí),接收到的推送消息offLine值均為YES
    // 判斷app是否是點(diǎn)擊通知欄消息進(jìn)行喚醒或開啟
    // 如果是點(diǎn)擊icon圖標(biāo)使得app進(jìn)入前臺(tái),則不做操作,并且同一條推送通知,此方法只執(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運(yùn)行時(shí)恢復(fù)個(gè)推sdk運(yùn)行

- (void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    /// Background Fetch 恢復(fù)SDK 運(yùn)行
    [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運(yùn)行狀態(tài)通知 */
- (void)GeTuiSDkDidNotifySdkState:(SdkStatus)aStatus {
    // 通知SDK運(yùn)行狀態(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)閉");
}

在通知欄點(diǎn)擊進(jìn)來的時(shí)候做角標(biāo)的變化

- (void)handlePushMessage:(NSDictionary *)dict notification:(UILocalNotification *)localNotification {
    //開始處理從通知欄點(diǎn)擊進(jìn)來的推送消息
    
    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;
    }
}

注冊(cè)本地通知消息

#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)建一個(gè)包含待通知內(nèi)容的 UNMutableNotificationContent 對(duì)象,注意不是 UNNotificationContent ,此對(duì)象為不可變對(duì)象。
    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ā)通知的時(shí)間
    NSDate *fireDate = [NSDate dateWithTimeIntervalSinceNow:alertTime];
    NSLog(@"fireDate=%@",fireDate);
    
    notification.fireDate = fireDate;
    // 時(shí)區(qū)
    notification.timeZone = [NSTimeZone defaultTimeZone];
    // 設(shè)置重復(fù)的間隔-不重復(fù)
    notification.repeatInterval = kCFCalendarUnitEra;
    
    // 通知內(nèi)容
    notification.alertBody = title;
    notification.applicationIconBadgeNumber = 1;
    // 通知被觸發(fā)時(shí)播放的聲音
    notification.soundName = UILocalNotificationDefaultSoundName;
    // 通知參數(shù)
    NSDictionary *userDict = [NSDictionary dictionaryWithObject:mes forKey:@"key"];
    notification.userInfo = userDict;
    
    // ios8后,需要添加這個(gè)注冊(cè),才能得到授權(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í)行通知注冊(cè)
    [[UIApplication sharedApplication] scheduleLocalNotification:notification];
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:[UIApplication sharedApplication].applicationIconBadgeNumber+1];
    [GeTuiSdk setBadge:[UIApplication sharedApplication].applicationIconBadgeNumber];
}

在進(jìn)入前臺(tái)的時(shí)候要將所有app角標(biāo)清空,同時(shí)告訴個(gè)推此時(shí)角標(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];
    //推送個(gè)數(shù)大于0
    if (application.applicationIconBadgeNumber>0) {  //badge number 不為0,說明程序有那個(gè)圈圈圖標(biāo)
        //這里進(jìn)行有關(guān)處理
        [application setApplicationIconBadgeNumber:0];   //將圖標(biāo)清零。
        [GeTuiSdk setBadge:0];
    }
}

至此,個(gè)推的遠(yuǎn)程推送和本地通知完成。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容