AppDelegate.mm 16 KB

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