AppDelegate.mm 22 KB

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