iOS開(kāi)發(fā)個(gè)推集成中的注意點(diǎn)(手動(dòng)集成)

一、個(gè)推的集成

1.個(gè)推的集成可以參考個(gè)推的集成文檔。

2.初步集成的代碼如下:

APPDelegate.h

#import <UIKit/UIKit.h>

// 個(gè)推SDK頭文件和相關(guān)信息宏(測(cè)試)
#import "GeTuiSdk.h"
#define kGtAppId     @"個(gè)推平臺(tái)登記應(yīng)用后的AppId"
#define kGtAppKey    @"個(gè)推平臺(tái)登記應(yīng)用后的AppKey"
#define kGtAppSecret @"個(gè)推平臺(tái)登記應(yīng)用后的AppSecret"

@interface AppDelegate : UIResponder <UIApplicationDelegate, GeTuiSdkDelegate>

@property (strong, nonatomic) UIWindow *window;


@end

APPDelegate.m

#import "ViewController.h"

// iOS10 及以上需導(dǎo)入 UserNotifications.framework
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
#import <UserNotifications/UserNotifications.h>
#endif


@interface AppDelegate ()<UNUserNotificationCenterDelegate>

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
 
    // [ GTSdk ]:是否運(yùn)行電子圍欄Lbs功能和是否SDK主動(dòng)請(qǐng)求用戶定位
    [GeTuiSdk lbsLocationEnable:YES andUserVerify:YES];
    
    // [ GTSdk ]:自定義渠道
    [GeTuiSdk setChannelId:@"GT-Channel"];
    
    // [ GTSdk ]:使用APPID/APPKEY/APPSECRENT啟動(dòng)個(gè)推
    [GeTuiSdk startSdkWithAppId:kGtAppId appKey:kGtAppKey appSecret:kGtAppSecret delegate:self];
    
    // 注冊(cè)APNs - custom method - 開(kāi)發(fā)者自定義的方法
    [self registerRemoteNotification];
    

    
    // 啟動(dòng)頁(yè)延時(shí)加載
    [NSThread sleepForTimeInterval:3.0];
    
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    
    self.window.backgroundColor = [UIColor whiteColor];

    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:[[ViewController alloc] init] ];

    self.window.rootViewController = nav;
    
    [self.window makeKeyAndVisible];

    [IQKeyboardManager sharedManager].enable = YES;

    return YES;
    
}

- (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.
}


- (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.
}


- (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 ========= 個(gè)推相關(guān)代碼 ==========
- (NSString *)formateTime:(NSDate *)date {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"HH:mm:ss"];
    NSString *dateTime = [formatter stringFromDate:date];
    return dateTime;
}

#pragma mark - background fetch  喚醒
- (void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
    // [ GTSdk ]:Background Fetch 恢復(fù)SDK 運(yùn)行
    [GeTuiSdk resume];
    
    completionHandler(UIBackgroundFetchResultNewData);
}

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

/** 注冊(cè)遠(yuǎn)程通知 */
- (void)registerRemoteNotification {
    /*
     警告:Xcode8的需要手動(dòng)開(kāi)啟“TARGETS -> Capabilities -> Push Notifications”
     */
    
    /*
     警告:該方法需要開(kāi)發(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];
    }
}

#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);
    
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"token" message:token delegate:nil cancelButtonTitle:@"cancle" otherButtonTitles:@"ok", nil];
    [alertView show];
    
    // [ GTSdk ]:向個(gè)推服務(wù)器注冊(cè)deviceToken
    [GeTuiSdk registerDeviceToken:token];
}

/** 遠(yuǎn)程通知注冊(cè)失敗委托 */
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    NSLog(@"%@", error.localizedDescription);
}

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

/** APP已經(jīng)接收到“遠(yuǎn)程”通知(推送) - (App運(yùn)行在后臺(tái))  */
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler {
    
    // [ GTSdk ]:將收到的APNs信息傳給個(gè)推統(tǒng)計(jì)
    [GeTuiSdk handleRemoteNotification:userInfo];
    
    // 顯示APNs信息到頁(yè)面
    NSString *record = [NSString stringWithFormat:@"[APN]%@, %@", [NSDate date], userInfo];
    NSLog(@"%@", record);
    
    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);
}

//  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);
    
    [GeTuiSdk resetBadge]; //重置角標(biāo)計(jì)數(shù)
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0]; // APP 清空角標(biāo)
    
    // [ GTSdk ]:將收到的APNs信息傳給個(gè)推統(tǒng)計(jì)
    [GeTuiSdk handleRemoteNotification:response.notification.request.content.userInfo];
    
    completionHandler();
}
#endif


#pragma mark - GeTuiSdkDelegate

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

/** 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];
    }
    
    // 頁(yè)面顯示日志
    NSString *record = [NSString stringWithFormat:@" %@, %@%@", [self formateTime:[NSDate date]], payloadMsg, offLine ? @"<離線消息>" : @""];
    NSLog(@"%@", record);
    
    // 控制臺(tái)打印日志
    NSString *msg = [NSString stringWithFormat:@"%@ : %@%@", [self formateTime:[NSDate date]], payloadMsg, offLine ? @"<離線消息>" : @""];
    NSLog(@">>[GTSdk ReceivePayload]:%@, taskId: %@, msgId :%@", msg, taskId, msgId);
}

/** SDK收到sendMessage消息回調(diào) */
- (void)GeTuiSdkDidSendMessage:(NSString *)messageId result:(int)result {
    // 頁(yè)面顯示:上行消息結(jié)果反饋
    NSString *record = [NSString stringWithFormat:@"Received sendmessage:%@ result:%d", messageId, result];
    NSLog(@"%@", record);
}

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

/** SDK運(yùn)行狀態(tài)通知 */
- (void)GeTuiSDkDidNotifySdkState:(SdkStatus)aStatus {
    // 頁(yè)面顯示更新通知SDK運(yùn)行狀態(tài)
    NSLog(@"%d", aStatus);
//    [_viewController updateStatusView:self];
}

/** SDK設(shè)置推送模式回調(diào)  */
- (void)GeTuiSdkDidSetPushMode:(BOOL)isModeOff error:(NSError *)error {
    // 頁(yè)面顯示錯(cuò)誤信息
    if (error) {
        NSLog(@"%@", error.localizedDescription);
        return;
    }
    
//    [_viewController logMsg:[NSString stringWithFormat:@">>>[GexinSdkSetModeOff]: %@", isModeOff ? @"開(kāi)啟" : @"關(guān)閉"]];
//    
//    // 頁(yè)面更新按鈕事件
//    UIViewController *vc = _naviController.topViewController;
//    if ([vc isKindOfClass:[ViewController class]]) {
//        ViewController *nextController = (ViewController *) vc;
//        [nextController updateModeOffButton:isModeOff];
//    }
}

@end

至此,基本的代碼集成就完成了,可以進(jìn)行相關(guān)的測(cè)試了。

二、個(gè)推平臺(tái)需要做的準(zhǔn)備

1.上傳APNs的.p12證書(shū),關(guān)于證書(shū)的請(qǐng)求和轉(zhuǎn)換可以參考如下鏈接:http://docs.getui.com/mobile/ios/apns/

2.完成證書(shū)上傳后,我們就可以運(yùn)行程序了。運(yùn)行程序我們需要拿到注冊(cè)推送服務(wù)器完成后的設(shè)備的:device token。

運(yù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)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

  • 極光推送: 1.JPush當(dāng)前版本是1.8.2,其SDK的開(kāi)發(fā)除了正常的功能完善和擴(kuò)展外也緊隨蘋(píng)果官方的步伐,SD...
    Isspace閱讀 6,886評(píng)論 10 16
  • Android 自定義View的各種姿勢(shì)1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 179,323評(píng)論 25 708
  • 前言 iOS10下,遠(yuǎn)程推送發(fā)生了變化,新增的UserNotifications.framework將本地推送和遠(yuǎn)...
    夭Y夭閱讀 1,221評(píng)論 2 10
  • 剛看過(guò)新上映的《我不是潘金蓮》之后,便對(duì)潘金蓮這個(gè)人物有些想法,大家不要想污了,我不是對(duì)這個(gè)人有想法,我只是對(duì)這個(gè)...
    請(qǐng)叫我三叔閱讀 821評(píng)論 4 4
  • 本已在腦海里消失的記憶因?yàn)檫@份作業(yè)全部恢復(fù)了出來(lái),這個(gè)記憶是我與大寶的,那個(gè)時(shí)候小寶兩個(gè)多月,都是吃飽睡睡飽吃...
    時(shí)光漫步_dc5c閱讀 365評(píng)論 0 0

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