AppDelegate.mm 17 KB

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