AppDelegate.mm 17 KB

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