You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native iOS后台任务实现咨询:APP关闭时每日凌晨发送本地通知

React Native iOS: Daily Background Task & Local Notifications (Even When App Is Closed)

Hey there! Great question—this is totally achievable on iOS with React Native, but you do need to work within Apple's strict background execution rules and combine RN with either native setup or trusted libraries. Let me break down your options clearly:


Option 1: Fixed Daily Local Notifications (Works When App Is Closed)

If your only need is to send a static daily notification at midnight (no dynamic logic like fetching fresh data first), this is straightforward. iOS’s native UNCalendarNotificationTrigger handles scheduling repeat notifications, and the system will deliver them even if your app is fully closed.

How to implement with React Native:

Use @react-native-community/push-notification-ios (a widely maintained library) to set this up:

  1. Install the library and configure iOS notification permissions (add the required entries to your Info.plist and enable Notification capabilities in Xcode).
  2. Request user permission for notifications:
    import PushNotificationIOS from '@react-native-community/push-notification-ios';
    
    PushNotificationIOS.requestPermissions({
      alert: true,
      sound: true,
      badge: false,
    });
    
  3. Schedule the daily midnight notification:
    const scheduleDailyMidnightNotification = () => {
      const midnight = new Date();
      midnight.setHours(0, 0, 0, 0); // Set time to 00:00
    
      PushNotificationIOS.scheduleLocalNotification({
        alertTitle: "Daily Reminder",
        alertBody: "This is your midnight notification!",
        sound: "default",
        trigger: {
          year: midnight.getFullYear(),
          month: midnight.getMonth() + 1,
          day: midnight.getDate(),
          hour: 0,
          minute: 0,
          repeats: true, // Enable daily repeat
        },
      });
    };
    
    // Call this when your app starts (e.g., in App.js's useEffect)
    scheduleDailyMidnightNotification();
    

This works reliably even if the app is closed because iOS’s system manages the notification trigger.


Option 2: Dynamic Background Logic + Notifications

If you need to run custom code at midnight (like fetching new data from a server before sending a notification), things get a bit trickier because iOS restricts background execution. You have two main paths here:

Sub-option A: Background App Refresh

iOS’s Background App Refresh lets your app wake up briefly in the background to perform tasks (max 30 seconds). The catch? iOS doesn’t guarantee exact timing—it schedules based on user habits, battery life, and other factors. But you can hint to the system to prioritize your app.

Use the react-native-background-fetch library to implement this:

  1. Install the library and enable the "Background App Refresh" capability in Xcode.
  2. Set up the background task:
    import BackgroundFetch from 'react-native-background-fetch';
    
    const initBackgroundTask = async () => {
      BackgroundFetch.configure({
        minimumFetchInterval: 15, // iOS enforces a 15-minute minimum (system may use longer intervals)
        stopOnTerminate: false, // Note: This won't work if the user manually closes the app
      }, async (taskId) => {
        // Run your custom logic here (e.g., fetch data from API)
        const freshData = await fetch('https://your-api.com/daily-update');
        
        // Send local notification with the new data
        PushNotificationIOS.presentLocalNotification({
          alertTitle: "Daily Update",
          alertBody: freshData.message,
          sound: "default",
        });
    
        // Tell iOS your task is done
        BackgroundFetch.finish(taskId);
      }, (error) => {
        console.error('Background Fetch failed:', error);
      });
    
      // Start the background task
      BackgroundFetch.start();
    };
    
    // Initialize on app start
    initBackgroundTask();
    

Critical Note: If the user manually closes your app (swipes it away from the multitasker), Background App Refresh will pause until the user opens the app again. iOS doesn’t allow apps to run background tasks after being explicitly terminated by the user.

Sub-option B: Silent Push Notifications

For precise timing (guaranteed midnight execution), use silent push notifications from your server. A silent push wakes your app in the background, lets you run code, and then you can send a local notification. This requires a server to send the push at the desired time, plus APNs (Apple Push Notification service) setup.

Use @react-native-firebase/messaging (or a similar push library) to handle this:

  1. Configure Firebase Messaging (or direct APNs) and enable the "Remote notifications" background mode in Xcode.
  2. Listen for background messages:
    import messaging from '@react-native-firebase/messaging';
    
    // Handle silent push notifications in the background
    messaging().setBackgroundMessageHandler(async (remoteMessage) => {
      // Run your custom logic here
      const freshData = await fetch('https://your-api.com/daily-update');
      
      // Send local notification
      await messaging().localNotification({
        title: "Daily Update",
        body: freshData.message,
        sound: "default",
      });
    });
    

Your server sends a silent push with the content-available: 1 flag at midnight, which triggers the background handler. This works even if the app is closed (as long as the user hasn’t disabled push permissions).


Key Takeaways for 2022 (and beyond)

Yes, React Native can absolutely handle this—you just need to align with iOS’s background rules:

  • For static notifications: Use calendar-triggered local notifications (most reliable, no server needed).
  • For dynamic logic: Use silent pushes for precise timing (requires server) or Background App Refresh (no server, but timing isn’t guaranteed).
  • Always test edge cases (like app closure, low battery) to ensure reliability.

Just remember to follow Apple’s App Store guidelines—don’t abuse background tasks, or your app might get rejected.

内容的提问来源于stack exchange,提问作者Egeberk Öz.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 13:57:37