此次即友盟分享小結(友盟分享小結 - iOS)之后對推送也進行了一版優化.此次分享內容依然基於已經成功集成 SDK 后 code 層級部分.
注:此次分享基於 SDK 3.1.0,若版本相差較大,僅供參考.
極光推送官方文檔: https://docs.jiguang.cn/jpush/guideline/intro/
首先,為分享單獨創建了一個類,為了可以更加清晰的划分其內容部分.


注:創建該子類后,切記將其頭文件引入到 AppDelegate 類中.
#import "AppDelegate.h" // Push #import "AppDelegate+JPush.h"
其次,將項目工程中配置相關配置.

最后,便是具體 code 相關內容,將申請的相關 key 預先設置成宏准備好,方便使用和變更時進行調用和更改.
一.聲明
優先將初始化的相關接口配置聲明准備好.
#import "AppDelegate.h" @interface AppDelegate (JPush) /** JPush 注冊 @param launchOptions 啟動項 */ - (void)registerJPush:(NSDictionary *)launchOptions; @end
將子類中聲明的方法在 AppDelegate 的方法中調用.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
// UserDefaults 相關
[[DZSBUserInfo sharedInstance] loadCacheData];
// CoreData 相關
[[CoreDataManager sharedCoreDataManager] managedObjectContext];
// 友盟相關
[self umAssociatedDetailSettings];
// Push
[self registerJPush:launchOptions];
// Root VC
[self setRootViewController];
return YES;
}
二.實現
1.引入所需的頭文件
2.實現聲明類中接口
3.實現具體方法和代理事件
#import "AppDelegate+JPush.h"
#import <JPUSHService.h>
// iOS10注冊APNs所需頭文件
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif
// 如果需要使用idfa功能所需要引入的頭文件(可選)
#import <AdSupport/AdSupport.h>
static NSString *appKey = JPush_APPKEY;
static NSString *channel = JPush_CHANNEL;// @"AppStore"
static BOOL isProduction = FALSE;
@interface AppDelegate () <JPUSHRegisterDelegate>
@end
@implementation AppDelegate (JPush)
- (void)registerJPush:(NSDictionary *)launchOptions {
//Required
//notice: 3.0.0及以后版本注冊可以這樣寫,也可以繼續用之前的注冊方式
JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
// 可以添加自定義categories
// NSSet<UNNotificationCategory *> *categories for iOS10 or later
// NSSet<UIUserNotificationCategory *> *categories for iOS8 and iOS9
}
[JPUSHService registerForRemoteNotificationConfig:entity delegate:self];// 注冊
// apn 內容獲取:
// NSDictionary *remoteNotification = [launchOptions objectForKey: UIApplicationLaunchOptionsRemoteNotificationKey];
// 監聽自定義消息
[kNotificationCenter addObserver:self
selector:@selector(networkDidReceiveMessage:)
name:kJPFNetworkDidReceiveMessageNotification
object:nil];
// Optional
// 獲取IDFA
// 如需使用IDFA功能請添加此代碼並在初始化方法的advertisingIdentifier參數中填寫對應值
NSString *advertisingId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
// Required
// init Push
// notice: 2.1.5版本的SDK新增的注冊方法,改成可上報IDFA,如果沒有使用IDFA直接傳nil
// 如需繼續使用pushConfig.plist文件聲明appKey等配置內容,請依舊使用[JPUSHService setupWithOption:launchOptions]方式初始化。
// [JPUSHService setupWithOption:launchOptions
// appKey:appKey
// channel:channel
// apsForProduction:isProduction];
[JPUSHService setupWithOption:launchOptions
appKey:appKey
channel:channel
apsForProduction:isProduction
advertisingIdentifier:nil];
[JPUSHService registrationIDCompletionHandler:^(int resCode, NSString *registrationID) {
NSLog(@"JPush --- resCode : %d,registrationID: %@",resCode,registrationID);
// [JPUSHService setDebugMode];
[JPUSHService setLogOFF];// 生成環境調用
}];
}
/**
獲取自定義消息推送內容
content:獲取推送的內容
messageID:獲取推送的messageID(key為@"_j_msgid")
extras:獲取用戶自定義參數
customizeField1:根據自定義key獲取自定義的value
@param notification 結構體
*/
- (void)networkDidReceiveMessage:(NSNotification *)notification {
/*
接收消息樣式
{
content = "\U7529\U9505\U7ed9IOS\Uff01";
extras = {
fFunPageUrl = "www.baidu.com";
fType = 2;
};
title = "\U6d4b\U8bd5";
}
*/
NSDictionary * userInfo = [notification userInfo];
/** 消息標題*/
NSString *content = [userInfo valueForKey:@"content"];
/** 消息內容*/
NSDictionary *extras = [userInfo valueForKey:@"extras"];
NSString *messageID = [userInfo valueForKey:@"_j_msgid"];
NSString *customizeField1 = [extras valueForKey:@"customizeField1"]; //服務端傳遞的Extras附加字段,key是自己定義的
}
#pragma mark - Delegate
/**
Required - 注冊 DeviceToken
注:
JPush 3.0.9 之前的版本,必須調用此接口,注冊 token 之后才可以登錄極光,使用通知和自定義消息功能。
從 JPush 3.0.9 版本開始,不調用此方法也可以登錄極光。但是不能使用APNs通知功能,只可以使用JPush自定義消息。
@param application 應用
@param deviceToken 標識
*/
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
[JPUSHService registerDeviceToken:deviceToken];
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
// Required,For systems with less than or equal to iOS6
// 取得 APNs 標准信息內容
NSDictionary *aps = [userInfo valueForKey:@"aps"];
NSString *content = [aps valueForKey:@"alert"]; //推送顯示的內容
NSInteger badge = [[aps valueForKey:@"badge"] integerValue]; //badge數量
NSString *sound = [aps valueForKey:@"sound"]; //播放的聲音
// 取得Extras字段內容
NSString *customizeField1 = [userInfo valueForKey:@"customizeExtras"]; //服務端中Extras字段,key是自己定義的
NSLog(@"JPush\ncontent =[%@], badge=[%ld], sound=[%@], customize field =[%@]",content,(long)badge,sound,customizeField1);
[JPUSHService handleRemoteNotification:userInfo];
NSLog(@"JPush - Receive notice\n%@", userInfo);
// iOS badge 清0
application.applicationIconBadgeNumber = 0;
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
// Required, iOS 7 Support
[JPUSHService handleRemoteNotification:userInfo];
// 應用正處理前台狀態下,不會收到推送消息,因此在此處需要額外處理一下
if (application.applicationState == UIApplicationStateActive) {
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:@"收到推送消息"
message:userInfo[@"aps"][@"alert"]
delegate:nil
cancelButtonTitle:@"取消"
otherButtonTitles:@"確定",nil];
[alert show];
}
NSLog(@"JPush - Receive notice\n%@", userInfo);
// 收到通知處理相關事項 contentType(系統消息 & 系統公告
NSString *contentType = [NSString stringWithFormat:@"%@", [userInfo objectForKey:@"contentType"]];
// 消息集合
NSMutableDictionary *dicMessage = [[NSMutableDictionary alloc] init];
if ([contentType isEqualToString:@""]) {//系統消息
// do somethings
} else if ([contentType isEqualToString:@""]){//系統公告
// do somethings
}
// block 回調
completionHandler(UIBackgroundFetchResultNewData);
}
/**
注冊 APNs 失敗
@param application 應用
@param error 異常
*/
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(nonnull NSError *)error {
//Optional
NSLog(@"JPush --- did Fail To Register For Remote Notifications With Error: %@\nLocalizedDescription: %@", error, error.localizedDescription);
}
#pragma mark- JPUSHRegisterDelegate
// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler API_AVAILABLE(ios(10.0)){
// Required
NSDictionary * userInfo = notification.request.content.userInfo;
if (@available(iOS 10.0, *)) {
if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
[JPUSHService handleRemoteNotification:userInfo];
}
} else {
// Fallback on earlier versions
}
if (@available(iOS 10.0, *)) {
completionHandler(UNNotificationPresentationOptionAlert);// 需要執行這個方法,選擇是否提醒用戶,有Badge、Sound、Alert三種類型可以選擇設置
} else {
// Fallback on earlier versions
}
}
// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler API_AVAILABLE(ios(10.0)){
// Required
NSDictionary * userInfo = response.notification.request.content.userInfo;
if (@available(iOS 10.0, *)) {
if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
[JPUSHService handleRemoteNotification:userInfo];
}
} else {
// Fallback on earlier versions
}
completionHandler(); // 系統要求執行這個方法
}
@end
注:以上實現部分所分享的內容是針對集成后的基本對接部分,其中不包含接收消息后的具體業務邏輯,具體業務邏輯需要根據產品需求在代理回調部分進行單獨自行定制開發.
分享內容中可能存在的縮寫內容部分 code 如下:
#pragma mark - 縮寫 #define kApplication [UIApplication sharedApplication] #define kKeyWindow [UIApplication sharedApplication].keyWindow #define kAppDelegate ((AppDelegate*)[UIApplication sharedApplication].delegate) #define kUserDefaults [NSUserDefaults standardUserDefaults] #define kNotificationCenter [NSNotificationCenter defaultCenter]
以上便是此次分享的全部內容,較為簡易的推送小結,具體還以實際需求為准,可以自行 diy 調整,希望對大家有所幫助,也希望大神多多指點共進步!
