一、個(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)行程序按后的截圖如下: