AppDelegate.mm 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  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.timestamp = [[NSDate date] timeIntervalSince1970]*1000;
  192. self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(postNotificationData:) userInfo:response repeats:YES];
  193. }
  194. //iOS 10 消息事件回调
  195. - (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler: (void (^)(void))completionHandler {
  196. NSDictionary * userInfo = response.notification.request.content.userInfo;
  197. if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
  198. // Apns
  199. NSLog(@"iOS 10 APNS 消息事件回调");
  200. // [JPUSHService handleRemoteNotification:userInfo];
  201. // // 保障应用被杀死状态下,用户点击推送消息,打开app后可以收到点击通知事件
  202. // [[RCTJPushEventQueue sharedInstance]._notificationQueue insertObject:userInfo atIndex:0];
  203. // [[NSNotificationCenter defaultCenter] postNotificationName:J_APNS_NOTIFICATION_OPENED_EVENT object:userInfo];
  204. }
  205. else {
  206. // 本地通知
  207. NSLog(@"iOS 10 本地通知 消息事件回调");
  208. // 保障应用被杀死状态下,用户点击推送消息,打开app后可以收到点击通知事件
  209. // [[RCTJPushEventQueue sharedInstance]._localNotificationQueue insertObject:userInfo atIndex:0];
  210. // [[NSNotificationCenter defaultCenter] postNotificationName:J_LOCAL_NOTIFICATION_OPENED_EVENT object:userInfo];
  211. }
  212. self.timestamp = [[NSDate date] timeIntervalSince1970]*1000;
  213. self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(postNotificationData:) userInfo:response repeats:YES];
  214. // NSString *categoryIdentifier = response.notification.request.content.categoryIdentifier;
  215. // [self.nativeBridge.bridge.eventDispatcher sendAppEventWithName:@"notificationReceive" body:@{@"category_id":categoryIdentifier,@"action_id":response.actionIdentifier}];
  216. // 处理用户交互
  217. // if ([response.actionIdentifier isEqualToString:@"ALLOW_ACTION"]) {
  218. // // 用户点击了"允许"按钮,发起网络请求
  219. // NSLog(@"User allow the request");
  220. //
  221. //// [self.nativeBridge.bridge.eventDispatcher sendAppEventWithName:@"notificationReceive" body:@{@"name":@"1",@"value":@"2"}];
  222. //
  223. //// [self makeNetworkRequest];
  224. // } else if ([response.actionIdentifier isEqualToString:@"DENY_ACTION"]) {
  225. // // 用户点击了"拒绝"按钮
  226. // NSLog(@"User denied the request");
  227. //// [self makeNetworkRequest];
  228. // } else if ([response.actionIdentifier isEqualToString:@"START_TIMER_NOW"]){
  229. // if ([categoryIdentifier isEqualToString:@"REMINDER_FS_START_FAST"]){
  230. //
  231. // }
  232. // else if ([categoryIdentifier isEqualToString:@"REMINDER_FS_START_SLEEP"]){
  233. //
  234. // }
  235. // } else if ([response.actionIdentifier isEqualToString:@"PICK_EARLIER_START"]){
  236. // if ([categoryIdentifier isEqualToString:@"REMINDER_FS_START_FAST"]){
  237. //
  238. // }
  239. // else if ([categoryIdentifier isEqualToString:@"REMINDER_FS_START_SLEEP"]){
  240. //
  241. // }
  242. // }
  243. // else if ([response.actionIdentifier isEqualToString:@"END_TIMER_NOW"]){
  244. //
  245. // }
  246. // else if ([response.actionIdentifier isEqualToString:@"PICK_EARLIER_END"]){
  247. //
  248. // }
  249. // else if ([response.actionIdentifier isEqualToString:@"SKIP"]){
  250. //
  251. // }
  252. // 系统要求执行这个方法
  253. completionHandler();
  254. }
  255. - (void)postNotificationData:(NSTimer *)timerInfo{
  256. if (self.rnLoaded){
  257. UNNotificationResponse *response = timerInfo.userInfo;
  258. [self.timer invalidate];
  259. self.timer = nil;
  260. NSString *categoryIdentifier = response.notification.request.content.categoryIdentifier;
  261. NSString *identifier = response.notification.request.identifier;
  262. if ([identifier hasPrefix:@"REMINDER_FS_"]){
  263. NSString *strId = [identifier substringFromIndex:12];
  264. [self.nativeBridge.bridge.eventDispatcher sendAppEventWithName:@"notificationReceive" body:@{@"category_id":categoryIdentifier,@"action_id":response.actionIdentifier,@"id":strId,@"timestamp":@(self.timestamp)}];
  265. [self clearAllDeliveredNotifications];
  266. }
  267. }
  268. else {
  269. }
  270. }
  271. - (void)jumpNotificationSettingPage{
  272. if (self.rnLoaded){
  273. [self.timer invalidate];
  274. self.timer = nil;
  275. [self.nativeBridge.bridge.eventDispatcher sendAppEventWithName:@"openNotificationSetting" body:@{}];
  276. }
  277. else {
  278. }
  279. }
  280. - (void)makeNetworkRequest{
  281. //https://api.fast.dev.liveplus.fun/api/static-resource-urls
  282. NSURL *url = [NSURL URLWithString:@"https://api.fast.dev.liveplus.fun/api/static-resource-urls"];
  283. NSURLRequest *request = [NSURLRequest requestWithURL:url];
  284. NSURLSessionDataTask *dataTask = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
  285. if (error) {
  286. NSLog(@"Error: %@", error.localizedDescription);
  287. } else {
  288. // 处理返回的数据
  289. NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
  290. NSLog(@"Response: %@", json);
  291. }
  292. }];
  293. [dataTask resume];
  294. }
  295. //自定义消息
  296. - (void)networkDidReceiveMessage:(NSNotification *)notification {
  297. NSDictionary * userInfo = [notification userInfo];
  298. // [[NSNotificationCenter defaultCenter] postNotificationName:J_CUSTOM_NOTIFICATION_EVENT object:userInfo];
  299. }
  300. - (void)demo{
  301. // 1. 设置 notification 内容
  302. UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
  303. content.title = @"Daily Reminder";
  304. content.body = @"It's 9:00 AM, time to start your day!";
  305. content.sound = [UNNotificationSound defaultSound];
  306. // 2. 设置触发条件 - 每天 9:00 AM
  307. NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
  308. dateComponents.hour = 9;
  309. dateComponents.minute = 0;
  310. UNCalendarNotificationTrigger *trigger = [UNCalendarNotificationTrigger triggerWithDateMatchingComponents:dateComponents repeats:YES];
  311. // 3. 创建 notification request
  312. UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"DailyReminder" content:content trigger:trigger];
  313. // 4. 添加 notification request 到通知中心
  314. UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
  315. [center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
  316. if (error != nil) {
  317. NSLog(@"Error adding notification request: %@", error);
  318. }
  319. }];
  320. }
  321. - (void)scheduleCalendarNotificationWithTitle:(NSString *)title body:(NSString *)body date:(NSDate *)date repeats:(BOOL)repeats identifier:(NSString *)identifier {
  322. NSLog(@"%s", __FUNCTION__);
  323. UNMutableNotificationContent *content = [UNMutableNotificationContent new];
  324. content.title = title;
  325. content.body = body;
  326. NSCalendar *calendar = NSCalendar.currentCalendar;
  327. NSDateComponents *components = [calendar components:(NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond) fromDate:date];
  328. UNCalendarNotificationTrigger *trigger = [UNCalendarNotificationTrigger triggerWithDateMatchingComponents:components repeats:repeats];
  329. UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:identifier content:content trigger:trigger];
  330. [[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
  331. if (error) {
  332. NSLog(@"%@", error);
  333. }
  334. }];
  335. }
  336. - (void)clearAllDeliveredNotifications {
  337. UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
  338. [center removeAllDeliveredNotifications];
  339. }
  340. - (void)userNotificationCenter:(UNUserNotificationCenter *)center openSettingsForNotification:(nullable UNNotification *)notification{
  341. self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(jumpNotificationSettingPage) userInfo:nil repeats:YES];
  342. }
  343. @end