AppDelegate.mm 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  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. #import <AVFoundation/AVFoundation.h>
  17. static NSString *const kRNConcurrentRoot = @"concurrentRoot";
  18. @interface AppDelegate () <RCTCxxBridgeDelegate, RCTTurboModuleManagerDelegate> {
  19. RCTTurboModuleManager *_turboModuleManager;
  20. RCTSurfacePresenterBridgeAdapter *_bridgeAdapter;
  21. std::shared_ptr<const facebook::react::ReactNativeConfig> _reactNativeConfig;
  22. facebook::react::ContextContainer::Shared _contextContainer;
  23. }
  24. @end
  25. #endif
  26. @interface AppDelegate()
  27. @property (nonatomic, strong) AVAudioPlayer *audioPlayer;
  28. @end
  29. @implementation AppDelegate
  30. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
  31. {
  32. // [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenNotificationSettingsURLString]];
  33. // NSString *url = UIApplicationOpenNotificationSettingsURLString;
  34. // APNS
  35. // BOOL isLocation = [CLLocationManager locationServicesEnabled];
  36. UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
  37. self.rnLoaded = NO;
  38. NSDate *date = [NSDate date];
  39. //zone为当前时区信息 在我的程序中打印的是@"Asia/Shanghai"
  40. NSTimeZone *zone = [NSTimeZone systemTimeZone];
  41. //所在地区时间与协调世界时差距
  42. NSInteger interval = [zone secondsFromGMTForDate: date];
  43. //加上时差,得到本地时间
  44. NSDate *localeDate = [date dateByAddingTimeInterval: interval];
  45. // JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
  46. // if (@available(iOS 12.0, *)) {
  47. // entity.types = JPAuthorizationOptionNone; //JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSou//nd|JPAuthorizationOptionProvidesAppNotificationSettings;
  48. // }
  49. // [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
  50. RCTAppSetupPrepareApp(application);
  51. RCTBridge *bridge = [self.reactDelegate createBridgeWithDelegate:self launchOptions:launchOptions];
  52. // UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
  53. center.delegate = self;
  54. #if RCT_NEW_ARCH_ENABLED
  55. _contextContainer = std::make_shared<facebook::react::ContextContainer const>();
  56. _reactNativeConfig = std::make_shared<facebook::react::EmptyReactNativeConfig const>();
  57. _contextContainer->insert("ReactNativeConfig", _reactNativeConfig);
  58. _bridgeAdapter = [[RCTSurfacePresenterBridgeAdapter alloc] initWithBridge:bridge contextContainer:_contextContainer];
  59. bridge.surfacePresenter = _bridgeAdapter.surfacePresenter;
  60. #endif
  61. NSDictionary *initProps = [self prepareInitialProps];
  62. UIView *rootView = [self.reactDelegate createRootViewWithBridge:bridge moduleName:@"taroDemo" initialProperties:initProps];
  63. if (@available(iOS 13.0, *)) {
  64. rootView.backgroundColor = [UIColor systemBackgroundColor];
  65. } else {
  66. rootView.backgroundColor = [UIColor blackColor];
  67. }
  68. self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
  69. self.window.backgroundColor = [UIColor blackColor];
  70. UIViewController *rootViewController = [self.reactDelegate createRootViewController];
  71. rootViewController.view = rootView;
  72. rootViewController.view.backgroundColor = [UIColor blackColor];
  73. self.window.rootViewController = rootViewController;
  74. [self.window makeKeyAndVisible];
  75. [super application:application didFinishLaunchingWithOptions:launchOptions];
  76. [self clearAllDeliveredNotifications];
  77. // [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(demoPush) userInfo:nil repeats:NO];
  78. // [self mixAudio];
  79. // [self demoPush];
  80. return YES;
  81. }
  82. -(void)demoPush{
  83. UNNotificationAction *action = [UNNotificationAction actionWithIdentifier:@"actionIdentifier" title:@"Action Title" options:UNNotificationActionOptionAuthenticationRequired];
  84. // 接着定义一个分类,并将动作添加到分类中
  85. UNNotificationCategory *category = [UNNotificationCategory categoryWithIdentifier:@"categoryIdentifier" actions:@[action] intentIdentifiers:@[] options:UNNotificationCategoryOptionCustomDismissAction];
  86. // 注册分类
  87. [[UNUserNotificationCenter currentNotificationCenter] setNotificationCategories:[NSSet setWithObjects:category, nil]];
  88. // 创建本地推送内容
  89. UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
  90. content.title = @"Notification Title";
  91. content.body = @"This is the notification body";
  92. content.categoryIdentifier = @"categoryIdentifier"; // 使用你刚刚定义的分类标识符
  93. // 创建推送请求
  94. UNTimeIntervalNotificationTrigger * trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:5 repeats:NO];
  95. UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"notificationIdentifier" content:content trigger:trigger];
  96. // 将推送请求添加到通知中心
  97. [[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:nil];
  98. }
  99. - (void)mixAudio{
  100. NSError *error = nil;
  101. AVMutableComposition *composition = [AVMutableComposition composition];
  102. // 创建音轨
  103. AVMutableCompositionTrack *compositionTrack = [composition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];
  104. // 声音文件路径
  105. NSString *soundFilePath1 = [[NSBundle mainBundle] pathForResource:@"1" ofType:@"m4a"];
  106. NSString *soundFilePath2 = [[NSBundle mainBundle] pathForResource:@"2" ofType:@"m4a"];
  107. // 加载音频文件
  108. AVAsset *asset1 = [AVAsset assetWithURL:[NSURL fileURLWithPath:soundFilePath1]];
  109. AVAsset *asset2 = [AVAsset assetWithURL:[NSURL fileURLWithPath:soundFilePath2]];
  110. // 获取音频文件的时长
  111. CMTimeRange timeRange1 = CMTimeRangeMake(kCMTimeZero, asset1.duration);
  112. CMTimeRange timeRange2 = CMTimeRangeMake(kCMTimeZero, asset2.duration);
  113. // 将音频文件的音轨添加到合成的音轨中
  114. [compositionTrack insertTimeRange:timeRange1 ofTrack:[[asset1 tracksWithMediaType:AVMediaTypeAudio] firstObject] atTime:kCMTimeZero error:&error];
  115. if (error) {
  116. // 错误处理
  117. NSLog(@"Error composing sound: %@", [error localizedDescription]);
  118. }
  119. // 在第一段声音之后继续添加第二段声音
  120. [compositionTrack insertTimeRange:timeRange2 ofTrack:[[asset2 tracksWithMediaType:AVMediaTypeAudio] firstObject] atTime:asset1.duration error:&error];
  121. if (error) {
  122. // 错误处理
  123. NSLog(@"Error composing sound: %@", [error localizedDescription]);
  124. }
  125. // 输出文件路径
  126. NSString *outputFilePath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"outputSound.m4a"];
  127. NSFileManager *fileManager = [NSFileManager defaultManager];
  128. BOOL fileExists = [fileManager fileExistsAtPath:outputFilePath];
  129. if (fileExists) {
  130. // 文件存在,删除文件
  131. NSError *error;
  132. BOOL success = [fileManager removeItemAtPath:outputFilePath error:&error];
  133. if (success) {
  134. NSLog(@"文件删除成功");
  135. } else {
  136. // 处理错误
  137. NSLog(@"文件删除失败: %@", [error localizedDescription]);
  138. }
  139. } else {
  140. NSLog(@"文件不存在");
  141. }
  142. NSURL *outputURL = [NSURL fileURLWithPath:outputFilePath];
  143. // 导出合成的音频
  144. AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:composition presetName:AVAssetExportPresetAppleM4A];
  145. exportSession.outputURL = outputURL;
  146. exportSession.outputFileType = AVFileTypeAppleM4A;
  147. [exportSession exportAsynchronouslyWithCompletionHandler:^{
  148. if (exportSession.status == AVAssetExportSessionStatusCompleted) {
  149. // 导出成功,可以播放或者使用输出的文件
  150. NSLog(@"Export success: %@", outputFilePath);
  151. NSURL *fileURL = [NSURL fileURLWithPath:outputFilePath];
  152. NSError *error;
  153. self->_audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:&error];
  154. if (error) {
  155. NSLog(@"Error creating audio player: %@", [error localizedDescription]);
  156. } else {
  157. [self->_audioPlayer play];
  158. }
  159. } else {
  160. // 导出失败,处理错误
  161. NSLog(@"Export failed: %@", [[exportSession error] localizedDescription]);
  162. }
  163. }];
  164. }
  165. - (void)applicationDidBecomeActive:(UIApplication *)application {
  166. [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
  167. }
  168. - (void)registerForPushNotifications {
  169. UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
  170. [center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert | UNAuthorizationOptionSound | UNAuthorizationOptionBadge) completionHandler:^(BOOL granted, NSError * _Nullable error) {
  171. if (granted) {
  172. dispatch_async(dispatch_get_main_queue(), ^{
  173. [[UIApplication sharedApplication] registerForRemoteNotifications];
  174. });
  175. } else {
  176. // 用户拒绝通知或发生错误
  177. }
  178. }];
  179. }
  180. /// This method controls whether the `concurrentRoot`feature of React18 is turned on or off.
  181. ///
  182. /// @see: https://reactjs.org/blog/2022/03/29/react-v18.html
  183. /// @note: This requires to be rendering on Fabric (i.e. on the New Architecture).
  184. /// @return: `true` if the `concurrentRoot` feture is enabled. Otherwise, it returns `false`.
  185. - (BOOL)concurrentRootEnabled
  186. {
  187. // Switch this bool to turn on and off the concurrent root
  188. return true;
  189. }
  190. - (NSDictionary *)prepareInitialProps
  191. {
  192. NSMutableDictionary *initProps = [NSMutableDictionary new];
  193. #ifdef RCT_NEW_ARCH_ENABLED
  194. initProps[kRNConcurrentRoot] = @([self concurrentRootEnabled]);
  195. #endif
  196. return initProps;
  197. }
  198. - (NSURL *)sourceURLForBridge:(RCTBridge *)bridge
  199. {
  200. // return [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];
  201. #if DEBUGaa
  202. return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index"];
  203. #else
  204. return [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];
  205. #endif
  206. }
  207. #if RCT_NEW_ARCH_ENABLED
  208. #pragma mark - RCTCxxBridgeDelegate
  209. - (std::unique_ptr<facebook::react::JSExecutorFactory>)jsExecutorFactoryForBridge:(RCTBridge *)bridge
  210. {
  211. _turboModuleManager = [[RCTTurboModuleManager alloc] initWithBridge:bridge
  212. delegate:self
  213. jsInvoker:bridge.jsCallInvoker];
  214. return RCTAppSetupDefaultJsExecutorFactory(bridge, _turboModuleManager);
  215. }
  216. #pragma mark RCTTurboModuleManagerDelegate
  217. - (Class)getModuleClassFromName:(const char *)name
  218. {
  219. return RCTCoreModulesClassProvider(name);
  220. }
  221. - (std::shared_ptr<facebook::react::TurboModule>)getTurboModule:(const std::string &)name
  222. jsInvoker:(std::shared_ptr<facebook::react::CallInvoker>)jsInvoker
  223. {
  224. return nullptr;
  225. }
  226. - (std::shared_ptr<facebook::react::TurboModule>)getTurboModule:(const std::string &)name
  227. initParams:
  228. (const facebook::react::ObjCTurboModule::InitParams &)params
  229. {
  230. return nullptr;
  231. }
  232. - (id<RCTTurboModule>)getModuleInstanceFromClass:(Class)moduleClass
  233. {
  234. return RCTAppSetupDefaultModuleFromClass(moduleClass);
  235. }
  236. #endif
  237. //************************************************JPush start************************************************
  238. //注册 APNS 成功并上报 DeviceToken
  239. - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
  240. // [JPUSHService registerDeviceToken:deviceToken];
  241. }
  242. - (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error{
  243. NSLog(@"get notification error");
  244. }
  245. //iOS 7 APNS
  246. - (void)application:(UIApplication *)application didReceiveRemoteNotification: (NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
  247. // iOS 10 以下 Required
  248. NSLog(@"iOS 7 APNS");
  249. // [JPUSHService handleRemoteNotification:userInfo];
  250. // [[NSNotificationCenter defaultCenter] postNotificationName:J_APNS_NOTIFICATION_ARRIVED_EVENT object:userInfo];
  251. completionHandler(UIBackgroundFetchResultNewData);
  252. }
  253. //iOS 10 前台收到消息
  254. - (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
  255. NSDictionary * userInfo = notification.request.content.userInfo;
  256. if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
  257. // Apns
  258. NSLog(@"iOS 10 APNS 前台收到消息");
  259. // [JPUSHService handleRemoteNotification:userInfo];
  260. // [[NSNotificationCenter defaultCenter] postNotificationName:J_APNS_NOTIFICATION_ARRIVED_EVENT object:userInfo];
  261. }
  262. else {
  263. // 本地通知 todo
  264. NSLog(@"iOS 10 本地通知 前台收到消息");
  265. // [[NSNotificationCenter defaultCenter] postNotificationName:J_LOCAL_NOTIFICATION_ARRIVED_EVENT object:userInfo];
  266. }
  267. //需要执行这个方法,选择是否提醒用户,有 Badge、Sound、Alert 三种类型可以选择设置
  268. completionHandler(UNNotificationPresentationOptionAlert);
  269. }
  270. - (void)didReceiveNotificationRequest:(UNNotificationRequest *)request withContentHandler:(void (^)(UNNotificationContent * _Nonnull))contentHandler {
  271. }
  272. //再实现UNUserNotificationCenterDelegate代理的方法
  273. //- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler
  274. //{
  275. // //应用在前台时候接收到本地推送通知、远程推送通知调用此方法
  276. //}
  277. - (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)(void))completionHandler
  278. {
  279. //应用程序在后台,用户通过点击本地推送、远程推送进入app时调用此方法
  280. self.timestamp = [[NSDate date] timeIntervalSince1970]*1000;
  281. self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(postNotificationData:) userInfo:response repeats:YES];
  282. }
  283. //iOS 10 消息事件回调
  284. - (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler: (void (^)(void))completionHandler {
  285. NSDictionary * userInfo = response.notification.request.content.userInfo;
  286. if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
  287. // Apns
  288. NSLog(@"iOS 10 APNS 消息事件回调");
  289. // [JPUSHService handleRemoteNotification:userInfo];
  290. // // 保障应用被杀死状态下,用户点击推送消息,打开app后可以收到点击通知事件
  291. // [[RCTJPushEventQueue sharedInstance]._notificationQueue insertObject:userInfo atIndex:0];
  292. // [[NSNotificationCenter defaultCenter] postNotificationName:J_APNS_NOTIFICATION_OPENED_EVENT object:userInfo];
  293. }
  294. else {
  295. // 本地通知
  296. NSLog(@"iOS 10 本地通知 消息事件回调");
  297. // 保障应用被杀死状态下,用户点击推送消息,打开app后可以收到点击通知事件
  298. // [[RCTJPushEventQueue sharedInstance]._localNotificationQueue insertObject:userInfo atIndex:0];
  299. // [[NSNotificationCenter defaultCenter] postNotificationName:J_LOCAL_NOTIFICATION_OPENED_EVENT object:userInfo];
  300. }
  301. self.timestamp = [[NSDate date] timeIntervalSince1970]*1000;
  302. self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(postNotificationData:) userInfo:response repeats:YES];
  303. // NSString *categoryIdentifier = response.notification.request.content.categoryIdentifier;
  304. // [self.nativeBridge.bridge.eventDispatcher sendAppEventWithName:@"notificationReceive" body:@{@"category_id":categoryIdentifier,@"action_id":response.actionIdentifier}];
  305. // 处理用户交互
  306. // if ([response.actionIdentifier isEqualToString:@"ALLOW_ACTION"]) {
  307. // // 用户点击了"允许"按钮,发起网络请求
  308. // NSLog(@"User allow the request");
  309. //
  310. //// [self.nativeBridge.bridge.eventDispatcher sendAppEventWithName:@"notificationReceive" body:@{@"name":@"1",@"value":@"2"}];
  311. //
  312. //// [self makeNetworkRequest];
  313. // } else if ([response.actionIdentifier isEqualToString:@"DENY_ACTION"]) {
  314. // // 用户点击了"拒绝"按钮
  315. // NSLog(@"User denied the request");
  316. //// [self makeNetworkRequest];
  317. // } else if ([response.actionIdentifier isEqualToString:@"START_TIMER_NOW"]){
  318. // if ([categoryIdentifier isEqualToString:@"REMINDER_FS_START_FAST"]){
  319. //
  320. // }
  321. // else if ([categoryIdentifier isEqualToString:@"REMINDER_FS_START_SLEEP"]){
  322. //
  323. // }
  324. // } else if ([response.actionIdentifier isEqualToString:@"PICK_EARLIER_START"]){
  325. // if ([categoryIdentifier isEqualToString:@"REMINDER_FS_START_FAST"]){
  326. //
  327. // }
  328. // else if ([categoryIdentifier isEqualToString:@"REMINDER_FS_START_SLEEP"]){
  329. //
  330. // }
  331. // }
  332. // else if ([response.actionIdentifier isEqualToString:@"END_TIMER_NOW"]){
  333. //
  334. // }
  335. // else if ([response.actionIdentifier isEqualToString:@"PICK_EARLIER_END"]){
  336. //
  337. // }
  338. // else if ([response.actionIdentifier isEqualToString:@"SKIP"]){
  339. //
  340. // }
  341. // 系统要求执行这个方法
  342. completionHandler();
  343. }
  344. - (void)postNotificationData:(NSTimer *)timerInfo{
  345. if (self.rnLoaded){
  346. UNNotificationResponse *response = timerInfo.userInfo;
  347. [self.timer invalidate];
  348. self.timer = nil;
  349. NSString *categoryIdentifier = response.notification.request.content.categoryIdentifier;
  350. NSString *identifier = response.notification.request.identifier;
  351. if ([identifier hasPrefix:@"REMINDER_FS_"]){
  352. NSString *strId = [identifier substringFromIndex:12];
  353. [self.nativeBridge.bridge.eventDispatcher sendAppEventWithName:@"notificationReceive" body:@{@"category_id":categoryIdentifier,@"action_id":response.actionIdentifier,@"id":strId,@"timestamp":@(self.timestamp)}];
  354. [self clearAllDeliveredNotifications];
  355. }
  356. }
  357. else {
  358. }
  359. }
  360. - (void)jumpNotificationSettingPage{
  361. if (self.rnLoaded){
  362. [self.timer invalidate];
  363. self.timer = nil;
  364. [self.nativeBridge.bridge.eventDispatcher sendAppEventWithName:@"openNotificationSetting" body:@{}];
  365. }
  366. else {
  367. }
  368. }
  369. - (void)makeNetworkRequest{
  370. //https://api.fast.dev.liveplus.fun/api/static-resource-urls
  371. NSURL *url = [NSURL URLWithString:@"https://api.fast.dev.liveplus.fun/api/static-resource-urls"];
  372. NSURLRequest *request = [NSURLRequest requestWithURL:url];
  373. NSURLSessionDataTask *dataTask = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
  374. if (error) {
  375. NSLog(@"Error: %@", error.localizedDescription);
  376. } else {
  377. // 处理返回的数据
  378. NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
  379. NSLog(@"Response: %@", json);
  380. }
  381. }];
  382. [dataTask resume];
  383. }
  384. //自定义消息
  385. - (void)networkDidReceiveMessage:(NSNotification *)notification {
  386. NSDictionary * userInfo = [notification userInfo];
  387. // [[NSNotificationCenter defaultCenter] postNotificationName:J_CUSTOM_NOTIFICATION_EVENT object:userInfo];
  388. }
  389. - (void)demo{
  390. // 1. 设置 notification 内容
  391. UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
  392. content.title = @"Daily Reminder";
  393. content.body = @"It's 9:00 AM, time to start your day!";
  394. content.sound = [UNNotificationSound defaultSound];
  395. // 2. 设置触发条件 - 每天 9:00 AM
  396. NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
  397. dateComponents.hour = 9;
  398. dateComponents.minute = 0;
  399. UNCalendarNotificationTrigger *trigger = [UNCalendarNotificationTrigger triggerWithDateMatchingComponents:dateComponents repeats:YES];
  400. // 3. 创建 notification request
  401. UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"DailyReminder" content:content trigger:trigger];
  402. // 4. 添加 notification request 到通知中心
  403. UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
  404. [center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
  405. if (error != nil) {
  406. NSLog(@"Error adding notification request: %@", error);
  407. }
  408. }];
  409. }
  410. - (void)scheduleCalendarNotificationWithTitle:(NSString *)title body:(NSString *)body date:(NSDate *)date repeats:(BOOL)repeats identifier:(NSString *)identifier {
  411. NSLog(@"%s", __FUNCTION__);
  412. UNMutableNotificationContent *content = [UNMutableNotificationContent new];
  413. content.title = title;
  414. content.body = body;
  415. NSCalendar *calendar = NSCalendar.currentCalendar;
  416. NSDateComponents *components = [calendar components:(NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond) fromDate:date];
  417. UNCalendarNotificationTrigger *trigger = [UNCalendarNotificationTrigger triggerWithDateMatchingComponents:components repeats:repeats];
  418. UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:identifier content:content trigger:trigger];
  419. [[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
  420. if (error) {
  421. NSLog(@"%@", error);
  422. }
  423. }];
  424. }
  425. - (void)clearAllDeliveredNotifications {
  426. UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
  427. [center removeAllDeliveredNotifications];
  428. }
  429. - (void)userNotificationCenter:(UNUserNotificationCenter *)center openSettingsForNotification:(nullable UNNotification *)notification{
  430. self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(jumpNotificationSettingPage) userInfo:nil repeats:YES];
  431. }
  432. - (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler{
  433. NSLog(@"%@",notification);
  434. // [UIApplication sharedApplication].applicationIconBadgeNumber = 100;
  435. completionHandler(UNNotificationPresentationOptionSound | UNNotificationPresentationOptionAlert);
  436. }
  437. - (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
  438. // 处理推送消息
  439. NSLog(@"Received a notification: %@", notification.alertBody);
  440. }
  441. @end