FlutterAliyunPushPlugin.m 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. #import "FlutterAliyunPushPlugin.h"
  2. #import <CloudPushSDK/CloudPushSDK.h>
  3. // iOS 10 notification
  4. #import <UserNotifications/UserNotifications.h>
  5. #import <Flutter/Flutter.h>
  6. NSString * AliyunAppKey = @"";
  7. NSString * AliyunAppSecret = @"";
  8. const static NSString * onPushRegistSuccess = @"onPushRegistSuccess";
  9. const static NSString * onPushRegistError = @"onPushRegistError";
  10. const static NSString * onReceiverNotification = @"onReceiverNotification";
  11. const static NSString * onReceiverMessage = @"onReceiverMessage";
  12. @implementation FlutterAliyunPushPlugin {
  13. NSDictionary *_launchNotification;
  14. }
  15. +(void)initKey:(NSString *) appkey appSecret:(NSString *) appSecret {
  16. AliyunAppKey = appkey;
  17. AliyunAppSecret = appSecret;
  18. }
  19. + (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {
  20. FlutterMethodChannel* channel = [FlutterMethodChannel
  21. methodChannelWithName:@"aliyun_push"
  22. binaryMessenger:[registrar messenger]];
  23. FlutterAliyunPushPlugin* instance = [[FlutterAliyunPushPlugin alloc] init];
  24. instance.channel = channel;
  25. [registrar addMethodCallDelegate:instance channel:channel];
  26. [registrar addApplicationDelegate:instance];
  27. }
  28. -(void) callFlutter:(NSString *)eventName withDatas:(id _Nullable) datas {
  29. if(_channel == nil) {
  30. return;
  31. }
  32. [_channel invokeMethod:eventName arguments:datas];
  33. }
  34. - (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result {
  35. if ([@"getPlatformVersion" isEqualToString:call.method]) {
  36. result([@"iOS " stringByAppendingString:[[UIDevice currentDevice] systemVersion]]);
  37. } else {
  38. result(FlutterMethodNotImplemented);
  39. }
  40. }
  41. /**
  42. 初始化推送
  43. */
  44. -(void) initPush:(UIApplication *)application
  45. launchOptions:(NSDictionary *)launchOptions {
  46. // APNs注册,获取deviceToken并上报
  47. [self registerAPNS:application];
  48. // 初始化SDK
  49. [self initCloudPush:AliyunAppKey appSecret:AliyunAppSecret];
  50. // 监听推送通道打开动作
  51. [self listenerOnChannelOpened];
  52. // 监听推送消息到达
  53. [self registerMessageReceive];
  54. // 点击通知将App从关闭状态启动时,将通知打开回执上报
  55. [CloudPushSDK sendNotificationAck:launchOptions];
  56. }
  57. - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
  58. NSLog(@"plugin didRegisterForRemoteNotificationsWithDeviceToken ---");
  59. [CloudPushSDK registerDevice:deviceToken withCallback:^(CloudPushCallbackResult *res) {
  60. if (res.success) {
  61. NSLog(@"Register deviceToken success, deviceToken: %@", [CloudPushSDK getApnsDeviceToken]);
  62. } else {
  63. NSLog(@"Register deviceToken failed, error: %@", res.error);
  64. }
  65. }];
  66. }
  67. /*
  68. * APNs注册失败回调
  69. */
  70. - (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
  71. NSLog(@"didFailToRegisterForRemoteNotificationsWithError --- %@", error);
  72. }
  73. #pragma mark - AppDelegate
  74. //- (void)applicationDidBecomeActive:(UIApplication *)application {
  75. // NSLog(@"FlutterAliyunPushPlugin applicationDidBecomeActive----");
  76. //}
  77. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  78. NSLog(@"FlutterAliyunPushPlugin didFinishLaunchingWithOptions----");
  79. [self initPush:application launchOptions:launchOptions];
  80. if (launchOptions != nil) {
  81. _launchNotification = launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey];
  82. }
  83. if ([launchOptions valueForKey:UIApplicationLaunchOptionsLocalNotificationKey]) {
  84. NSLog(@"launchOptions has Notification----");
  85. UILocalNotification *localNotification = [launchOptions valueForKey:UIApplicationLaunchOptionsLocalNotificationKey];
  86. NSMutableDictionary *localNotificationEvent = @{}.mutableCopy;
  87. localNotificationEvent[@"content"] = localNotification.alertBody;
  88. localNotificationEvent[@"badge"] = @(localNotification.applicationIconBadgeNumber);
  89. localNotificationEvent[@"extras"] = localNotification.userInfo;
  90. localNotificationEvent[@"fireTime"] = [NSNumber numberWithLong:[localNotification.fireDate timeIntervalSince1970] * 1000];
  91. localNotificationEvent[@"soundName"] = [localNotification.soundName isEqualToString:UILocalNotificationDefaultSoundName] ? @"" : localNotification.soundName;
  92. if (@available(iOS 8.2, *)) {
  93. localNotificationEvent[@"title"] = localNotification.alertTitle;
  94. }
  95. _launchNotification = localNotificationEvent;
  96. }
  97. //[self performSelector:@selector(addNotificationWithDateTrigger) withObject:nil afterDelay:2];
  98. return YES;
  99. }
  100. //在后台未被干掉收到消息
  101. - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler {
  102. NSLog(@"didReceiveRemoteNotification------- Receive one notification.");
  103. // 取得APNS通知内容
  104. NSDictionary *aps = [userInfo valueForKey:@"aps"];
  105. // 内容
  106. NSString *content = [aps valueForKey:@"alert"];
  107. // badge数量
  108. NSInteger badge = [[aps valueForKey:@"badge"] integerValue];
  109. // 播放声音
  110. NSString *sound = [aps valueForKey:@"sound"];
  111. // 取得Extras字段内容
  112. NSString *Extras = [userInfo valueForKey:@"Extras"]; //服务端中Extras字段,key是自己定义的
  113. NSLog(@"content = [%@], badge = [%ld], sound = [%@], Extras = [%@]",
  114. content, (long)badge, sound, Extras);
  115. [self callFlutter:onReceiverNotification withDatas:userInfo];
  116. // iOS badge 清0
  117. application.applicationIconBadgeNumber = 0;
  118. // 通知打开回执上报
  119. [CloudPushSDK sendNotificationAck:userInfo];
  120. }
  121. #pragma mark APNs Register
  122. /**
  123. * 向APNs注册,获取deviceToken用于推送
  124. *
  125. * @param application
  126. */
  127. - (void)registerAPNS:(UIApplication *)application {
  128. float systemVersionNum = [[[UIDevice currentDevice] systemVersion] floatValue];
  129. if (systemVersionNum >= 10.0) {
  130. // iOS 10 notifications
  131. UNUserNotificationCenter* _notificationCenter = [UNUserNotificationCenter currentNotificationCenter];
  132. // 创建category,并注册到通知中心
  133. [self createCustomNotificationCategory];
  134. // 请求推送权限
  135. [_notificationCenter requestAuthorizationWithOptions:UNAuthorizationOptionAlert | UNAuthorizationOptionBadge | UNAuthorizationOptionSound completionHandler:^(BOOL granted, NSError * _Nullable error) {
  136. if (granted) {
  137. // granted
  138. NSLog(@"User authored notification.");
  139. // 向APNs注册,获取deviceToken
  140. dispatch_async(dispatch_get_main_queue(), ^{
  141. [application registerForRemoteNotifications];
  142. });
  143. } else {
  144. // not granted
  145. NSLog(@"User denied notification.");
  146. }
  147. }];
  148. } else if (systemVersionNum >= 8.0) {
  149. // iOS 8 Notifications
  150. #pragma clang diagnostic push
  151. #pragma clang diagnostic ignored"-Wdeprecated-declarations"
  152. [application registerUserNotificationSettings:
  153. [UIUserNotificationSettings settingsForTypes:
  154. (UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge)
  155. categories:nil]];
  156. [application registerForRemoteNotifications];
  157. #pragma clang diagnostic pop
  158. } else {
  159. // iOS < 8 Notifications
  160. #pragma clang diagnostic push
  161. #pragma clang diagnostic ignored"-Wdeprecated-declarations"
  162. [[UIApplication sharedApplication] registerForRemoteNotificationTypes:
  163. (UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound)];
  164. #pragma clang diagnostic pop
  165. }
  166. }
  167. /**
  168. * 创建并注册通知category(iOS 10+)
  169. */
  170. - (void)createCustomNotificationCategory {
  171. // 自定义`action1`和`action2`
  172. UNNotificationAction *action1 = [UNNotificationAction actionWithIdentifier:@"action1" title:@"test1" options: UNNotificationActionOptionNone];
  173. UNNotificationAction *action2 = [UNNotificationAction actionWithIdentifier:@"action2" title:@"test2" options: UNNotificationActionOptionNone];
  174. // 创建id为`test_category`的category,并注册两个action到category
  175. // UNNotificationCategoryOptionCustomDismissAction表明可以触发通知的dismiss回调
  176. UNNotificationCategory *category = [UNNotificationCategory categoryWithIdentifier:@"test_category" actions:@[action1, action2] intentIdentifiers:@[] options:
  177. UNNotificationCategoryOptionCustomDismissAction];
  178. // 注册category到通知中心
  179. UNUserNotificationCenter* _notificationCenter = [UNUserNotificationCenter currentNotificationCenter];
  180. [_notificationCenter setNotificationCategories:[NSSet setWithObjects:category, nil]];
  181. }
  182. #pragma mark SDK Init
  183. - (void)initCloudPush:(NSString*)appkey appSecret:(NSString*)appSecret {
  184. NSLog(@"start initCloudPush----");
  185. // 正式上线建议关闭
  186. [CloudPushSDK turnOnDebug];
  187. // SDK初始化,手动输出appKey和appSecret
  188. [CloudPushSDK asyncInit:appkey appSecret:appSecret callback:^(CloudPushCallbackResult *res) {
  189. if (res.success) {
  190. NSLog(@"Push SDK init success, deviceId: %@.", [CloudPushSDK getDeviceId]);
  191. [self callFlutter:onPushRegistSuccess withDatas:nil];
  192. } else {
  193. NSLog(@"Push SDK init failed, error: %@", res.error);
  194. [_channel invokeMethod:onPushRegistError arguments:res.error];
  195. [self callFlutter:onPushRegistError withDatas:res.error];
  196. }
  197. }];
  198. }
  199. /**
  200. * 注册推送通道打开监听
  201. */
  202. - (void)listenerOnChannelOpened {
  203. [[NSNotificationCenter defaultCenter] addObserver:self
  204. selector:@selector(onChannelOpened:)
  205. name:@"CCPDidChannelConnectedSuccess"
  206. object:nil];
  207. }
  208. /**
  209. * 推送通道打开回调
  210. *
  211. * @param notification
  212. */
  213. - (void)onChannelOpened:(NSNotification *)notification {
  214. NSLog(@"消息通道建立成功-----");
  215. }
  216. #pragma mark Receive Message
  217. /**
  218. * @brief 注册推送消息到来监听
  219. */
  220. - (void)registerMessageReceive {
  221. [[NSNotificationCenter defaultCenter] addObserver:self
  222. selector:@selector(onMessageReceived:)
  223. name:@"CCPDidReceiveMessageNotification"
  224. object:nil];
  225. }
  226. /**
  227. * 处理在前台到来推送消息
  228. *
  229. * @param notification
  230. */
  231. - (void)onMessageReceived:(NSNotification *)notification {
  232. NSLog(@"onMessageReceived------ Receive one message!");
  233. CCPSysMessage *message = [notification object];
  234. NSString *title = [[NSString alloc] initWithData:message.title encoding:NSUTF8StringEncoding];
  235. NSString *body = [[NSString alloc] initWithData:message.body encoding:NSUTF8StringEncoding];
  236. NSLog(@"Receive message title: %@, content: %@.", title, body);
  237. if(![NSThread isMainThread]) {
  238. dispatch_async(dispatch_get_main_queue(), ^{
  239. [self callFlutter:onReceiverMessage withDatas:body];
  240. });
  241. } else {
  242. [self callFlutter:onReceiverMessage withDatas:body];
  243. }
  244. }
  245. @end