AppDelegate.mm 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  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 <CoreLocation/CoreLocation.h>
  7. //#import <RCTJPushModule.h>
  8. #if RCT_NEW_ARCH_ENABLED
  9. #import <React/CoreModulesPlugins.h>
  10. #import <React/RCTCxxBridgeDelegate.h>
  11. #import <React/RCTFabricSurfaceHostingProxyRootView.h>
  12. #import <React/RCTSurfacePresenter.h>
  13. #import <React/RCTSurfacePresenterBridgeAdapter.h>
  14. #import <ReactCommon/RCTTurboModuleManager.h>
  15. #import <react/config/ReactNativeConfig.h>
  16. static NSString *const kRNConcurrentRoot = @"concurrentRoot";
  17. @interface AppDelegate () <RCTCxxBridgeDelegate, RCTTurboModuleManagerDelegate> {
  18. RCTTurboModuleManager *_turboModuleManager;
  19. RCTSurfacePresenterBridgeAdapter *_bridgeAdapter;
  20. std::shared_ptr<const facebook::react::ReactNativeConfig> _reactNativeConfig;
  21. facebook::react::ContextContainer::Shared _contextContainer;
  22. }
  23. @end
  24. #endif
  25. @implementation AppDelegate
  26. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
  27. {
  28. // [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenNotificationSettingsURLString]];
  29. // NSString *url = UIApplicationOpenNotificationSettingsURLString;
  30. // APNS
  31. // BOOL isLocation = [CLLocationManager locationServicesEnabled];
  32. self.rnLoaded = NO;
  33. NSDate *date = [NSDate date];
  34. //zone为当前时区信息 在我的程序中打印的是@"Asia/Shanghai"
  35. NSTimeZone *zone = [NSTimeZone systemTimeZone];
  36. //所在地区时间与协调世界时差距
  37. NSInteger interval = [zone secondsFromGMTForDate: date];
  38. //加上时差,得到本地时间
  39. NSDate *localeDate = [date dateByAddingTimeInterval: interval];
  40. // JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
  41. // if (@available(iOS 12.0, *)) {
  42. // entity.types = JPAuthorizationOptionNone; //JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSou//nd|JPAuthorizationOptionProvidesAppNotificationSettings;
  43. // }
  44. // [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
  45. RCTAppSetupPrepareApp(application);
  46. RCTBridge *bridge = [self.reactDelegate createBridgeWithDelegate:self launchOptions:launchOptions];
  47. UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
  48. center.delegate = self;
  49. #if RCT_NEW_ARCH_ENABLED
  50. _contextContainer = std::make_shared<facebook::react::ContextContainer const>();
  51. _reactNativeConfig = std::make_shared<facebook::react::EmptyReactNativeConfig const>();
  52. _contextContainer->insert("ReactNativeConfig", _reactNativeConfig);
  53. _bridgeAdapter = [[RCTSurfacePresenterBridgeAdapter alloc] initWithBridge:bridge contextContainer:_contextContainer];
  54. bridge.surfacePresenter = _bridgeAdapter.surfacePresenter;
  55. #endif
  56. NSDictionary *initProps = [self prepareInitialProps];
  57. UIView *rootView = [self.reactDelegate createRootViewWithBridge:bridge moduleName:@"taroDemo" initialProperties:initProps];
  58. if (@available(iOS 13.0, *)) {
  59. rootView.backgroundColor = [UIColor systemBackgroundColor];
  60. } else {
  61. rootView.backgroundColor = [UIColor blackColor];
  62. }
  63. self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
  64. self.window.backgroundColor = [UIColor blackColor];
  65. UIViewController *rootViewController = [self.reactDelegate createRootViewController];
  66. rootViewController.view = rootView;
  67. rootViewController.view.backgroundColor = [UIColor blackColor];
  68. self.window.rootViewController = rootViewController;
  69. [self.window makeKeyAndVisible];
  70. [super application:application didFinishLaunchingWithOptions:launchOptions];
  71. [self clearAllDeliveredNotifications];
  72. return YES;
  73. }
  74. - (void)applicationDidBecomeActive:(UIApplication *)application {
  75. [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
  76. }
  77. - (void)registerForPushNotifications {
  78. UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
  79. [center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert | UNAuthorizationOptionSound | UNAuthorizationOptionBadge) completionHandler:^(BOOL granted, NSError * _Nullable error) {
  80. if (granted) {
  81. dispatch_async(dispatch_get_main_queue(), ^{
  82. [[UIApplication sharedApplication] registerForRemoteNotifications];
  83. });
  84. } else {
  85. // 用户拒绝通知或发生错误
  86. }
  87. }];
  88. }
  89. /// This method controls whether the `concurrentRoot`feature of React18 is turned on or off.
  90. ///
  91. /// @see: https://reactjs.org/blog/2022/03/29/react-v18.html
  92. /// @note: This requires to be rendering on Fabric (i.e. on the New Architecture).
  93. /// @return: `true` if the `concurrentRoot` feture is enabled. Otherwise, it returns `false`.
  94. - (BOOL)concurrentRootEnabled
  95. {
  96. // Switch this bool to turn on and off the concurrent root
  97. return true;
  98. }
  99. - (NSDictionary *)prepareInitialProps
  100. {
  101. NSMutableDictionary *initProps = [NSMutableDictionary new];
  102. #ifdef RCT_NEW_ARCH_ENABLED
  103. initProps[kRNConcurrentRoot] = @([self concurrentRootEnabled]);
  104. #endif
  105. return initProps;
  106. }
  107. - (NSURL *)sourceURLForBridge:(RCTBridge *)bridge
  108. {
  109. // return [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];
  110. #if DEBUG
  111. return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index"];
  112. #else
  113. return [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];
  114. #endif
  115. }
  116. #if RCT_NEW_ARCH_ENABLED
  117. #pragma mark - RCTCxxBridgeDelegate
  118. - (std::unique_ptr<facebook::react::JSExecutorFactory>)jsExecutorFactoryForBridge:(RCTBridge *)bridge
  119. {
  120. _turboModuleManager = [[RCTTurboModuleManager alloc] initWithBridge:bridge
  121. delegate:self
  122. jsInvoker:bridge.jsCallInvoker];
  123. return RCTAppSetupDefaultJsExecutorFactory(bridge, _turboModuleManager);
  124. }
  125. #pragma mark RCTTurboModuleManagerDelegate
  126. - (Class)getModuleClassFromName:(const char *)name
  127. {
  128. return RCTCoreModulesClassProvider(name);
  129. }
  130. - (std::shared_ptr<facebook::react::TurboModule>)getTurboModule:(const std::string &)name
  131. jsInvoker:(std::shared_ptr<facebook::react::CallInvoker>)jsInvoker
  132. {
  133. return nullptr;
  134. }
  135. - (std::shared_ptr<facebook::react::TurboModule>)getTurboModule:(const std::string &)name
  136. initParams:
  137. (const facebook::react::ObjCTurboModule::InitParams &)params
  138. {
  139. return nullptr;
  140. }
  141. - (id<RCTTurboModule>)getModuleInstanceFromClass:(Class)moduleClass
  142. {
  143. return RCTAppSetupDefaultModuleFromClass(moduleClass);
  144. }
  145. #endif
  146. //************************************************JPush start************************************************
  147. //注册 APNS 成功并上报 DeviceToken
  148. - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
  149. // [JPUSHService registerDeviceToken:deviceToken];
  150. }
  151. - (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error{
  152. NSLog(@"get notification error");
  153. }
  154. //iOS 7 APNS
  155. - (void)application:(UIApplication *)application didReceiveRemoteNotification: (NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
  156. // iOS 10 以下 Required
  157. NSLog(@"iOS 7 APNS");
  158. // [JPUSHService handleRemoteNotification:userInfo];
  159. // [[NSNotificationCenter defaultCenter] postNotificationName:J_APNS_NOTIFICATION_ARRIVED_EVENT object:userInfo];
  160. completionHandler(UIBackgroundFetchResultNewData);
  161. }
  162. //iOS 10 前台收到消息
  163. - (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
  164. NSDictionary * userInfo = notification.request.content.userInfo;
  165. if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
  166. // Apns
  167. NSLog(@"iOS 10 APNS 前台收到消息");
  168. // [JPUSHService handleRemoteNotification:userInfo];
  169. // [[NSNotificationCenter defaultCenter] postNotificationName:J_APNS_NOTIFICATION_ARRIVED_EVENT object:userInfo];
  170. }
  171. else {
  172. // 本地通知 todo
  173. NSLog(@"iOS 10 本地通知 前台收到消息");
  174. // [[NSNotificationCenter defaultCenter] postNotificationName:J_LOCAL_NOTIFICATION_ARRIVED_EVENT object:userInfo];
  175. }
  176. //需要执行这个方法,选择是否提醒用户,有 Badge、Sound、Alert 三种类型可以选择设置
  177. completionHandler(UNNotificationPresentationOptionAlert);
  178. }
  179. - (void)didReceiveNotificationRequest:(UNNotificationRequest *)request withContentHandler:(void (^)(UNNotificationContent * _Nonnull))contentHandler {
  180. }
  181. //再实现UNUserNotificationCenterDelegate代理的方法
  182. //- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler
  183. //{
  184. // //应用在前台时候接收到本地推送通知、远程推送通知调用此方法
  185. //}
  186. - (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)(void))completionHandler
  187. {
  188. //应用程序在后台,用户通过点击本地推送、远程推送进入app时调用此方法
  189. self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(postNotificationData:) userInfo:response repeats:YES];
  190. }
  191. //iOS 10 消息事件回调
  192. - (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler: (void (^)(void))completionHandler {
  193. NSDictionary * userInfo = response.notification.request.content.userInfo;
  194. if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
  195. // Apns
  196. NSLog(@"iOS 10 APNS 消息事件回调");
  197. // [JPUSHService handleRemoteNotification:userInfo];
  198. // // 保障应用被杀死状态下,用户点击推送消息,打开app后可以收到点击通知事件
  199. // [[RCTJPushEventQueue sharedInstance]._notificationQueue insertObject:userInfo atIndex:0];
  200. // [[NSNotificationCenter defaultCenter] postNotificationName:J_APNS_NOTIFICATION_OPENED_EVENT object:userInfo];
  201. }
  202. else {
  203. // 本地通知
  204. NSLog(@"iOS 10 本地通知 消息事件回调");
  205. // 保障应用被杀死状态下,用户点击推送消息,打开app后可以收到点击通知事件
  206. // [[RCTJPushEventQueue sharedInstance]._localNotificationQueue insertObject:userInfo atIndex:0];
  207. // [[NSNotificationCenter defaultCenter] postNotificationName:J_LOCAL_NOTIFICATION_OPENED_EVENT object:userInfo];
  208. }
  209. self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(postNotificationData:) userInfo:response repeats:YES];
  210. // NSString *categoryIdentifier = response.notification.request.content.categoryIdentifier;
  211. // [self.nativeBridge.bridge.eventDispatcher sendAppEventWithName:@"notificationReceive" body:@{@"category_id":categoryIdentifier,@"action_id":response.actionIdentifier}];
  212. // 处理用户交互
  213. // if ([response.actionIdentifier isEqualToString:@"ALLOW_ACTION"]) {
  214. // // 用户点击了"允许"按钮,发起网络请求
  215. // NSLog(@"User allow the request");
  216. //
  217. //// [self.nativeBridge.bridge.eventDispatcher sendAppEventWithName:@"notificationReceive" body:@{@"name":@"1",@"value":@"2"}];
  218. //
  219. //// [self makeNetworkRequest];
  220. // } else if ([response.actionIdentifier isEqualToString:@"DENY_ACTION"]) {
  221. // // 用户点击了"拒绝"按钮
  222. // NSLog(@"User denied the request");
  223. //// [self makeNetworkRequest];
  224. // } else if ([response.actionIdentifier isEqualToString:@"START_TIMER_NOW"]){
  225. // if ([categoryIdentifier isEqualToString:@"REMINDER_FS_START_FAST"]){
  226. //
  227. // }
  228. // else if ([categoryIdentifier isEqualToString:@"REMINDER_FS_START_SLEEP"]){
  229. //
  230. // }
  231. // } else if ([response.actionIdentifier isEqualToString:@"PICK_EARLIER_START"]){
  232. // if ([categoryIdentifier isEqualToString:@"REMINDER_FS_START_FAST"]){
  233. //
  234. // }
  235. // else if ([categoryIdentifier isEqualToString:@"REMINDER_FS_START_SLEEP"]){
  236. //
  237. // }
  238. // }
  239. // else if ([response.actionIdentifier isEqualToString:@"END_TIMER_NOW"]){
  240. //
  241. // }
  242. // else if ([response.actionIdentifier isEqualToString:@"PICK_EARLIER_END"]){
  243. //
  244. // }
  245. // else if ([response.actionIdentifier isEqualToString:@"SKIP"]){
  246. //
  247. // }
  248. // 系统要求执行这个方法
  249. completionHandler();
  250. }
  251. - (void)postNotificationData:(NSTimer *)timerInfo{
  252. if (self.rnLoaded){
  253. UNNotificationResponse *response = timerInfo.userInfo;
  254. [self.timer invalidate];
  255. self.timer = nil;
  256. NSString *categoryIdentifier = response.notification.request.content.categoryIdentifier;
  257. NSString *identifier = response.notification.request.identifier;
  258. [self.nativeBridge.bridge.eventDispatcher sendAppEventWithName:@"notificationReceive" body:@{@"category_id":categoryIdentifier,@"action_id":response.actionIdentifier,@"id":identifier}];
  259. [self clearAllDeliveredNotifications];
  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. - (void)clearAllDeliveredNotifications {
  321. UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
  322. [center removeAllDeliveredNotifications];
  323. }
  324. @end