AJPushService.m 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. //
  2. // AJPushService.m
  3. // AJPushSDK
  4. //
  5. // Created by Black on 2021/2/2.
  6. // Copyright © 2018 anji-plus 安吉加加信息技术有限公司 http://www.anji-plus.com. All rights reserved.
  7. //
  8. #import "AJPushService.h"
  9. #import "AJPushDeviceInfo.h"
  10. // 引入 JPush 功能所需头文件
  11. #import <JPush/JPUSHService.h>
  12. // iOS10 注册 APNs 所需头文件
  13. #ifdef NSFoundationVersionNumber_iOS_9_x_Max
  14. #import <UserNotifications/UserNotifications.h>
  15. #endif
  16. #ifdef DEBUG
  17. # define AJDLog(fmt, ...) NSLog((@"[函数名:%s]" "[行号:%d]" fmt),__FUNCTION__, __LINE__, ##__VA_ARGS__);
  18. #else
  19. # define AJDLog(...);
  20. #endif
  21. NSString *const kAJPushServiceCustomMessageNotification = @"kAJPushServiceCustomMessageNotificationKey";//自定义消息
  22. NSString *const kAJPushServiceNoticeBarMessageNotification = @"kAJPushServiceNoticeBarMessageNotificationKey";//通知栏消息
  23. NSString *const kAJPushServiceInnerMessageNotification = @"kAJPushServiceInnerMessageNotificationKey";//内部消息提醒
  24. typedef enum {
  25. AJPushTypeApplication, //外部消息启动app获取
  26. AJPushTypeOuter,//app进入后台,消息栏唤醒
  27. AJPushTypeInner, //app前台消息提醒
  28. AJPushTypeCustomer //自定义消息
  29. } AJPushType;
  30. @interface AJPushService ()<JPUSHRegisterDelegate>
  31. @end
  32. @implementation AJPushService {
  33. BOOL _isProduction;
  34. NSString *_appKey;
  35. NSString *_ajAppKey;
  36. NSString *_channel;
  37. NSString *_baseUrl;
  38. }
  39. static AJPushService *__service;
  40. + (instancetype)shareService {
  41. static dispatch_once_t onceToken;
  42. dispatch_once(&onceToken, ^{
  43. __service = [[super allocWithZone:NULL] init];;
  44. });
  45. return __service;
  46. }
  47. + (instancetype)allocWithZone:(struct _NSZone *)zone{
  48. return [self shareService];
  49. }
  50. - (void)registerJPushOption:(NSDictionary *)launchingOption
  51. appKey:(NSString *)appKey
  52. ajAppKey:(NSString *)ajAppKey
  53. channel:(NSString *)channel
  54. apsForProduction:(BOOL)isProduction {
  55. _appKey = appKey;
  56. _ajAppKey = ajAppKey;
  57. _channel = channel;
  58. _isProduction = isProduction;
  59. [self initAPNS];
  60. [self initJPushWithOptions:launchingOption];
  61. [self initLocationNotification];
  62. }
  63. - (void)registerDeviceToken:(NSData *)deviceToken withUrl:(nullable NSString *)baseUrl {
  64. _baseUrl = baseUrl;
  65. if (_baseUrl == nil) {
  66. _baseUrl = @"http://appsp.test.anji-plus.com";
  67. }
  68. [JPUSHService registerDeviceToken:deviceToken];
  69. //获取registrationID
  70. [JPUSHService registrationIDCompletionHandler:^(int resCode, NSString *registrationID) {
  71. AJDLog(@"++ registrationID: %@", registrationID);
  72. [self requestWithRegistrationId:registrationID];
  73. self.registrationID = registrationID;
  74. }];
  75. }
  76. - (BOOL)isProduction {
  77. return _isProduction;
  78. }
  79. # pragma mark- 初始化极光服务
  80. //添加初始化 APNs 代码
  81. - (void)initAPNS {
  82. //notice: 3.0.0 及以后版本注册可以这样写,也可以继续用之前的注册方式
  83. JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
  84. if (@available(iOS 12.0, *)) {
  85. entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound|JPAuthorizationOptionProvidesAppNotificationSettings;
  86. } else {
  87. entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
  88. }
  89. [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
  90. }
  91. //初始化极光服务
  92. - (void)initJPushWithOptions:(NSDictionary *)launchOptions {
  93. [JPUSHService setupWithOption:launchOptions
  94. appKey:_appKey
  95. channel:_channel
  96. apsForProduction:_isProduction
  97. advertisingIdentifier:nil];
  98. NSDictionary *remoteNotification = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
  99. if(remoteNotification != nil) {
  100. [self handleNotification:remoteNotification type:AJPushTypeApplication];
  101. }
  102. }
  103. //初始化本地通知服务
  104. - (void)initLocationNotification {
  105. NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
  106. [defaultCenter addObserver:self selector:@selector(networkDidReceiveMessage:) name:kJPFNetworkDidReceiveMessageNotification object:nil];
  107. }
  108. //自定义消息接受通知
  109. - (void)networkDidReceiveMessage:(NSNotification *)notification {
  110. NSDictionary *userInfo = [notification userInfo];
  111. [self handleNotification:userInfo type:AJPushTypeCustomer];
  112. }
  113. // 通知栏进入 解析推送消息
  114. - (void)handleNotification:(NSDictionary *)info type:(AJPushType)type {
  115. NSString *notificationName = kAJPushServiceInnerMessageNotification;
  116. //控制延迟响应时间,避免异常
  117. float delayTime = 0.5;
  118. if (type == AJPushTypeOuter) {
  119. [self clearBadge];
  120. notificationName = kAJPushServiceNoticeBarMessageNotification;
  121. } else if (type == AJPushTypeInner) {
  122. delayTime = 0.1;
  123. notificationName = kAJPushServiceInnerMessageNotification;
  124. } else if (type == AJPushTypeCustomer) {
  125. delayTime = 0.1;
  126. notificationName = kAJPushServiceCustomMessageNotification;
  127. } else if (type == AJPushTypeApplication) {
  128. [self clearBadge];
  129. notificationName = kAJPushServiceNoticeBarMessageNotification;
  130. }
  131. NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
  132. dispatch_queue_t queue = dispatch_get_main_queue();
  133. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayTime * NSEC_PER_SEC)), queue, ^{
  134. [defaultCenter postNotificationName:notificationName object:self userInfo:info];
  135. });
  136. }
  137. //清除角标
  138. - (void)clearBadge {
  139. [UIApplication sharedApplication].applicationIconBadgeNumber = -1;
  140. [JPUSHService resetBadge];
  141. }
  142. #pragma mark- JPUSHRegisterDelegate
  143. // 通知栏进入 iOS 10 Support
  144. - (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler {
  145. // Required
  146. NSDictionary * userInfo = response.notification.request.content.userInfo;
  147. if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
  148. [self handleNotification:userInfo type:AJPushTypeOuter];
  149. }
  150. completionHandler(); // 系统要求执行这个方法
  151. }
  152. // 应用内推送提示、透传 iOS 10 Support
  153. - (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
  154. // Required
  155. NSDictionary * userInfo = notification.request.content.userInfo;
  156. if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
  157. [self handleNotification: userInfo type:AJPushTypeInner];
  158. }
  159. completionHandler(UNNotificationPresentationOptionSound); // 需要执行这个方法,选择是否提醒用户,有 Badge、Sound、Alert 三种类型可以选择设置
  160. }
  161. #pragma mark- 业务初始化请求
  162. - (void)requestWithRegistrationId:(NSString *)registrationId {
  163. NSString *baseUrl = [NSString stringWithFormat:@"%@/sp/push/init", _baseUrl];
  164. NSURL *url_post = [NSURL URLWithString: baseUrl];
  165. NSMutableURLRequest *request_post = [NSMutableURLRequest
  166. requestWithURL:url_post];
  167. request_post.HTTPMethod = @"POST";
  168. [request_post setValue:@"application/json" forHTTPHeaderField:@"Accept"];
  169. [request_post setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
  170. //获取设备信息
  171. NSString *brand = [AJPushDeviceInfo getBrandInfo];
  172. NSString *osVersion = [AJPushDeviceInfo getOSVerison];
  173. NSDictionary *reqParams = @{
  174. @"registrationId": registrationId,
  175. @"manuToken": registrationId,
  176. @"deviceId": registrationId,
  177. @"brand": brand,
  178. @"osVersion": osVersion,
  179. @"deviceType": @"5",
  180. @"appKey": _ajAppKey
  181. };
  182. AJDLog(@"url %@",baseUrl);
  183. AJDLog(@"params %@",reqParams);
  184. request_post.HTTPBody = [NSJSONSerialization dataWithJSONObject:reqParams options:NSJSONWritingPrettyPrinted error:nil];
  185. NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
  186. config.HTTPAdditionalHeaders = @{@"Accept": @"application/json"};
  187. NSURLSession *session_post = [NSURLSession sessionWithConfiguration:config];
  188. NSURLSessionDataTask *task_post = [session_post dataTaskWithRequest:request_post completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
  189. if (data) {
  190. NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
  191. AJDLog(@"data2dict:%@",dict);
  192. }
  193. }];
  194. [task_post resume];
  195. }
  196. - (void)dealloc
  197. {
  198. [[NSNotificationCenter defaultCenter] removeObserver:self];
  199. }
  200. @end