AppDelegate.mm 16 KB

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