AppDelegate.mm 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. #import "AppDelegate.h"
  2. #import <React/RCTBridge.h>
  3. #import <React/RCTBundleURLProvider.h>
  4. #import <React/RCTRootView.h>
  5. #import <React/RCTAppSetupUtils.h>
  6. #import <RCTJPushModule.h>
  7. #if RCT_NEW_ARCH_ENABLED
  8. #import <React/CoreModulesPlugins.h>
  9. #import <React/RCTCxxBridgeDelegate.h>
  10. #import <React/RCTFabricSurfaceHostingProxyRootView.h>
  11. #import <React/RCTSurfacePresenter.h>
  12. #import <React/RCTSurfacePresenterBridgeAdapter.h>
  13. #import <ReactCommon/RCTTurboModuleManager.h>
  14. #import <react/config/ReactNativeConfig.h>
  15. static NSString *const kRNConcurrentRoot = @"concurrentRoot";
  16. @interface AppDelegate () <RCTCxxBridgeDelegate, RCTTurboModuleManagerDelegate> {
  17. RCTTurboModuleManager *_turboModuleManager;
  18. RCTSurfacePresenterBridgeAdapter *_bridgeAdapter;
  19. std::shared_ptr<const facebook::react::ReactNativeConfig> _reactNativeConfig;
  20. facebook::react::ContextContainer::Shared _contextContainer;
  21. }
  22. @end
  23. #endif
  24. @implementation AppDelegate
  25. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
  26. {
  27. // [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenNotificationSettingsURLString]];
  28. // NSString *url = UIApplicationOpenNotificationSettingsURLString;
  29. // APNS
  30. self.rnLoaded = NO;
  31. NSDate *date = [NSDate date];
  32. //zone为当前时区信息 在我的程序中打印的是@"Asia/Shanghai"
  33. NSTimeZone *zone = [NSTimeZone systemTimeZone];
  34. //所在地区时间与协调世界时差距
  35. NSInteger interval = [zone secondsFromGMTForDate: date];
  36. //加上时差,得到本地时间
  37. NSDate *localeDate = [date dateByAddingTimeInterval: interval];
  38. JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
  39. if (@available(iOS 12.0, *)) {
  40. entity.types = JPAuthorizationOptionNone; //JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSou//nd|JPAuthorizationOptionProvidesAppNotificationSettings;
  41. }
  42. [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
  43. RCTAppSetupPrepareApp(application);
  44. RCTBridge *bridge = [self.reactDelegate createBridgeWithDelegate:self launchOptions:launchOptions];
  45. #if RCT_NEW_ARCH_ENABLED
  46. _contextContainer = std::make_shared<facebook::react::ContextContainer const>();
  47. _reactNativeConfig = std::make_shared<facebook::react::EmptyReactNativeConfig const>();
  48. _contextContainer->insert("ReactNativeConfig", _reactNativeConfig);
  49. _bridgeAdapter = [[RCTSurfacePresenterBridgeAdapter alloc] initWithBridge:bridge contextContainer:_contextContainer];
  50. bridge.surfacePresenter = _bridgeAdapter.surfacePresenter;
  51. #endif
  52. NSDictionary *initProps = [self prepareInitialProps];
  53. UIView *rootView = [self.reactDelegate createRootViewWithBridge:bridge moduleName:@"taroDemo" initialProperties:initProps];
  54. if (@available(iOS 13.0, *)) {
  55. rootView.backgroundColor = [UIColor systemBackgroundColor];
  56. } else {
  57. rootView.backgroundColor = [UIColor blackColor];
  58. }
  59. self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
  60. self.window.backgroundColor = [UIColor blackColor];
  61. UIViewController *rootViewController = [self.reactDelegate createRootViewController];
  62. rootViewController.view = rootView;
  63. rootViewController.view.backgroundColor = [UIColor blackColor];
  64. self.window.rootViewController = rootViewController;
  65. [self.window makeKeyAndVisible];
  66. [super application:application didFinishLaunchingWithOptions:launchOptions];
  67. // NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  68. // [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
  69. // NSDate *date1 = [dateFormatter dateFromString:@"2024-05-30 22:00:00"];
  70. // [self scheduleCalendarNotificationWithTitle:@"你好" body:@"推送" date:date1 repeats:YES identifier:@"push1"];
  71. // [self demo];
  72. // [self registerForPushNotifications];
  73. [NSTimer scheduledTimerWithTimeInterval:15.0
  74. target:self
  75. selector:@selector(timerFired:)
  76. userInfo:nil
  77. repeats:NO];
  78. [self clearAllDeliveredNotifications];
  79. return YES;
  80. }
  81. - (void)timerFired:(NSTimer *)timer {
  82. // 定时器触发后执行的代码
  83. NSLog(@"Timer fired!");
  84. // [self.nativeBridge.bridge.eventDispatcher sendAppEventWithName:@"notificationReceive" body:@{
  85. // @"title":@"hello",
  86. // @"value":@"world"
  87. // }];
  88. }
  89. - (void)registerForPushNotifications {
  90. UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
  91. [center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert | UNAuthorizationOptionSound | UNAuthorizationOptionBadge) completionHandler:^(BOOL granted, NSError * _Nullable error) {
  92. if (granted) {
  93. dispatch_async(dispatch_get_main_queue(), ^{
  94. [[UIApplication sharedApplication] registerForRemoteNotifications];
  95. });
  96. } else {
  97. // 用户拒绝通知或发生错误
  98. }
  99. }];
  100. }
  101. /// This method controls whether the `concurrentRoot`feature of React18 is turned on or off.
  102. ///
  103. /// @see: https://reactjs.org/blog/2022/03/29/react-v18.html
  104. /// @note: This requires to be rendering on Fabric (i.e. on the New Architecture).
  105. /// @return: `true` if the `concurrentRoot` feture is enabled. Otherwise, it returns `false`.
  106. - (BOOL)concurrentRootEnabled
  107. {
  108. // Switch this bool to turn on and off the concurrent root
  109. return true;
  110. }
  111. - (NSDictionary *)prepareInitialProps
  112. {
  113. NSMutableDictionary *initProps = [NSMutableDictionary new];
  114. #ifdef RCT_NEW_ARCH_ENABLED
  115. initProps[kRNConcurrentRoot] = @([self concurrentRootEnabled]);
  116. #endif
  117. return initProps;
  118. }
  119. - (NSURL *)sourceURLForBridge:(RCTBridge *)bridge
  120. {
  121. // return [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];
  122. #if DEBUGAAA
  123. return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index"];
  124. #else
  125. return [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];
  126. #endif
  127. }
  128. #if RCT_NEW_ARCH_ENABLED
  129. #pragma mark - RCTCxxBridgeDelegate
  130. - (std::unique_ptr<facebook::react::JSExecutorFactory>)jsExecutorFactoryForBridge:(RCTBridge *)bridge
  131. {
  132. _turboModuleManager = [[RCTTurboModuleManager alloc] initWithBridge:bridge
  133. delegate:self
  134. jsInvoker:bridge.jsCallInvoker];
  135. return RCTAppSetupDefaultJsExecutorFactory(bridge, _turboModuleManager);
  136. }
  137. #pragma mark RCTTurboModuleManagerDelegate
  138. - (Class)getModuleClassFromName:(const char *)name
  139. {
  140. return RCTCoreModulesClassProvider(name);
  141. }
  142. - (std::shared_ptr<facebook::react::TurboModule>)getTurboModule:(const std::string &)name
  143. jsInvoker:(std::shared_ptr<facebook::react::CallInvoker>)jsInvoker
  144. {
  145. return nullptr;
  146. }
  147. - (std::shared_ptr<facebook::react::TurboModule>)getTurboModule:(const std::string &)name
  148. initParams:
  149. (const facebook::react::ObjCTurboModule::InitParams &)params
  150. {
  151. return nullptr;
  152. }
  153. - (id<RCTTurboModule>)getModuleInstanceFromClass:(Class)moduleClass
  154. {
  155. return RCTAppSetupDefaultModuleFromClass(moduleClass);
  156. }
  157. #endif
  158. //************************************************JPush start************************************************
  159. //注册 APNS 成功并上报 DeviceToken
  160. - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
  161. [JPUSHService registerDeviceToken:deviceToken];
  162. }
  163. - (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error{
  164. NSLog(@"get notification error");
  165. }
  166. //iOS 7 APNS
  167. - (void)application:(UIApplication *)application didReceiveRemoteNotification: (NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
  168. // iOS 10 以下 Required
  169. NSLog(@"iOS 7 APNS");
  170. [JPUSHService handleRemoteNotification:userInfo];
  171. [[NSNotificationCenter defaultCenter] postNotificationName:J_APNS_NOTIFICATION_ARRIVED_EVENT object:userInfo];
  172. completionHandler(UIBackgroundFetchResultNewData);
  173. }
  174. //iOS 10 前台收到消息
  175. - (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
  176. NSDictionary * userInfo = notification.request.content.userInfo;
  177. if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
  178. // Apns
  179. NSLog(@"iOS 10 APNS 前台收到消息");
  180. [JPUSHService handleRemoteNotification:userInfo];
  181. [[NSNotificationCenter defaultCenter] postNotificationName:J_APNS_NOTIFICATION_ARRIVED_EVENT object:userInfo];
  182. }
  183. else {
  184. // 本地通知 todo
  185. NSLog(@"iOS 10 本地通知 前台收到消息");
  186. [[NSNotificationCenter defaultCenter] postNotificationName:J_LOCAL_NOTIFICATION_ARRIVED_EVENT object:userInfo];
  187. }
  188. //需要执行这个方法,选择是否提醒用户,有 Badge、Sound、Alert 三种类型可以选择设置
  189. completionHandler(UNNotificationPresentationOptionAlert);
  190. }
  191. - (void)didReceiveNotificationRequest:(UNNotificationRequest *)request withContentHandler:(void (^)(UNNotificationContent * _Nonnull))contentHandler {
  192. }
  193. //iOS 10 消息事件回调
  194. - (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler: (void (^)(void))completionHandler {
  195. NSDictionary * userInfo = response.notification.request.content.userInfo;
  196. if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
  197. // Apns
  198. NSLog(@"iOS 10 APNS 消息事件回调");
  199. [JPUSHService handleRemoteNotification:userInfo];
  200. // 保障应用被杀死状态下,用户点击推送消息,打开app后可以收到点击通知事件
  201. [[RCTJPushEventQueue sharedInstance]._notificationQueue insertObject:userInfo atIndex:0];
  202. [[NSNotificationCenter defaultCenter] postNotificationName:J_APNS_NOTIFICATION_OPENED_EVENT object:userInfo];
  203. }
  204. else {
  205. // 本地通知
  206. NSLog(@"iOS 10 本地通知 消息事件回调");
  207. // 保障应用被杀死状态下,用户点击推送消息,打开app后可以收到点击通知事件
  208. [[RCTJPushEventQueue sharedInstance]._localNotificationQueue insertObject:userInfo atIndex:0];
  209. [[NSNotificationCenter defaultCenter] postNotificationName:J_LOCAL_NOTIFICATION_OPENED_EVENT object:userInfo];
  210. }
  211. self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(postNotificationData:) userInfo:response repeats:YES];
  212. // NSString *categoryIdentifier = response.notification.request.content.categoryIdentifier;
  213. // [self.nativeBridge.bridge.eventDispatcher sendAppEventWithName:@"notificationReceive" body:@{@"category_id":categoryIdentifier,@"action_id":response.actionIdentifier}];
  214. // 处理用户交互
  215. // if ([response.actionIdentifier isEqualToString:@"ALLOW_ACTION"]) {
  216. // // 用户点击了"允许"按钮,发起网络请求
  217. // NSLog(@"User allow the request");
  218. //
  219. //// [self.nativeBridge.bridge.eventDispatcher sendAppEventWithName:@"notificationReceive" body:@{@"name":@"1",@"value":@"2"}];
  220. //
  221. //// [self makeNetworkRequest];
  222. // } else if ([response.actionIdentifier isEqualToString:@"DENY_ACTION"]) {
  223. // // 用户点击了"拒绝"按钮
  224. // NSLog(@"User denied the request");
  225. //// [self makeNetworkRequest];
  226. // } else if ([response.actionIdentifier isEqualToString:@"START_TIMER_NOW"]){
  227. // if ([categoryIdentifier isEqualToString:@"REMINDER_FS_START_FAST"]){
  228. //
  229. // }
  230. // else if ([categoryIdentifier isEqualToString:@"REMINDER_FS_START_SLEEP"]){
  231. //
  232. // }
  233. // } else if ([response.actionIdentifier isEqualToString:@"PICK_EARLIER_START"]){
  234. // if ([categoryIdentifier isEqualToString:@"REMINDER_FS_START_FAST"]){
  235. //
  236. // }
  237. // else if ([categoryIdentifier isEqualToString:@"REMINDER_FS_START_SLEEP"]){
  238. //
  239. // }
  240. // }
  241. // else if ([response.actionIdentifier isEqualToString:@"END_TIMER_NOW"]){
  242. //
  243. // }
  244. // else if ([response.actionIdentifier isEqualToString:@"PICK_EARLIER_END"]){
  245. //
  246. // }
  247. // else if ([response.actionIdentifier isEqualToString:@"SKIP"]){
  248. //
  249. // }
  250. // 系统要求执行这个方法
  251. completionHandler();
  252. }
  253. - (void)postNotificationData:(NSTimer *)timerInfo{
  254. if (self.rnLoaded){
  255. UNNotificationResponse *response = timerInfo.userInfo;
  256. [self.timer invalidate];
  257. self.timer = nil;
  258. NSString *categoryIdentifier = response.notification.request.content.categoryIdentifier;
  259. NSString *identifier = response.notification.request.identifier;
  260. [self.nativeBridge.bridge.eventDispatcher sendAppEventWithName:@"notificationReceive" body:@{@"category_id":categoryIdentifier,@"action_id":response.actionIdentifier,@"id":identifier}];
  261. [self clearAllDeliveredNotifications];
  262. }
  263. else {
  264. }
  265. }
  266. - (void)makeNetworkRequest{
  267. //https://api.fast.dev.liveplus.fun/api/static-resource-urls
  268. NSURL *url = [NSURL URLWithString:@"https://api.fast.dev.liveplus.fun/api/static-resource-urls"];
  269. NSURLRequest *request = [NSURLRequest requestWithURL:url];
  270. NSURLSessionDataTask *dataTask = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
  271. if (error) {
  272. NSLog(@"Error: %@", error.localizedDescription);
  273. } else {
  274. // 处理返回的数据
  275. NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
  276. NSLog(@"Response: %@", json);
  277. }
  278. }];
  279. [dataTask resume];
  280. }
  281. //自定义消息
  282. - (void)networkDidReceiveMessage:(NSNotification *)notification {
  283. NSDictionary * userInfo = [notification userInfo];
  284. [[NSNotificationCenter defaultCenter] postNotificationName:J_CUSTOM_NOTIFICATION_EVENT object:userInfo];
  285. }
  286. - (void)demo{
  287. // 1. 设置 notification 内容
  288. UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
  289. content.title = @"Daily Reminder";
  290. content.body = @"It's 9:00 AM, time to start your day!";
  291. content.sound = [UNNotificationSound defaultSound];
  292. // 2. 设置触发条件 - 每天 9:00 AM
  293. NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
  294. dateComponents.hour = 9;
  295. dateComponents.minute = 0;
  296. UNCalendarNotificationTrigger *trigger = [UNCalendarNotificationTrigger triggerWithDateMatchingComponents:dateComponents repeats:YES];
  297. // 3. 创建 notification request
  298. UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"DailyReminder" content:content trigger:trigger];
  299. // 4. 添加 notification request 到通知中心
  300. UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
  301. [center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
  302. if (error != nil) {
  303. NSLog(@"Error adding notification request: %@", error);
  304. }
  305. }];
  306. }
  307. - (void)scheduleCalendarNotificationWithTitle:(NSString *)title body:(NSString *)body date:(NSDate *)date repeats:(BOOL)repeats identifier:(NSString *)identifier {
  308. NSLog(@"%s", __FUNCTION__);
  309. UNMutableNotificationContent *content = [UNMutableNotificationContent new];
  310. content.title = title;
  311. content.body = body;
  312. NSCalendar *calendar = NSCalendar.currentCalendar;
  313. NSDateComponents *components = [calendar components:(NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond) fromDate:date];
  314. UNCalendarNotificationTrigger *trigger = [UNCalendarNotificationTrigger triggerWithDateMatchingComponents:components repeats:repeats];
  315. UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:identifier content:content trigger:trigger];
  316. [[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
  317. if (error) {
  318. NSLog(@"%@", error);
  319. }
  320. }];
  321. }
  322. - (void)clearAllDeliveredNotifications {
  323. UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
  324. [center removeAllDeliveredNotifications];
  325. }
  326. @end