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

如何实现用户退出APP时不再接收APNC通知?代码实现求助

How to Clear Notifications When Users Exit Your iOS App

Hey there! Let’s walk through exactly how to set up the code that clears pending notifications when users exit your app, and clarify where to place those lifecycle methods you’re asking about.

1. Where to Place applicationWillTerminate (and Its Scene-Based Equivalent)

First, the applicationWillTerminate(_:) method lives in your AppDelegate.swift file—this is the traditional home for app-wide lifecycle events. However, if your app targets iOS 13 or later and uses Scene Architecture (most modern apps do), you’ll also need to handle this in SceneDelegate.swift, since scene-based apps manage lifecycle per-window/scene instead of globally.

2. Implement the Notification Cleanup Code

For AppDelegate (Legacy or Non-Scene Apps)

Open your AppDelegate.swift and add or update the applicationWillTerminate method like this:

import UIKit
import UserNotifications

@main
class AppDelegate: UIResponder, UIApplicationDelegate {

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Don't forget to request notification permissions first (if you haven't already)
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { granted, error in
            if let error = error {
                print("Notification auth error: \(error.localizedDescription)")
            }
        }
        return true
    }

    // Triggered when the app is about to terminate (e.g., user swipes it away from multitask view, system kills it)
    func applicationWillTerminate(_ application: UIApplication) {
        // Clear all pending notification requests (those scheduled but not yet delivered)
        UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
        
        // Optional: If you also want to clear notifications already shown in the Notification Center, add this line:
        UNUserNotificationCenter.current().removeAllDeliveredNotifications()
    }
}

For SceneDelegate (iOS 13+ Scene-Based Apps)

If your app uses scenes, add the sceneWillTerminate method to your SceneDelegate.swift:

import UIKit
import UserNotifications

class SceneDelegate: UIResponder, UIWindowSceneDelegate {

    var window: UIWindow?

    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        guard let _ = (scene as? UIWindowScene) else { return }
    }

    // Triggered when the specific scene is about to terminate
    func sceneWillTerminate(_ scene: UIScene) {
        // Same cleanup code as above
        UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
        UNUserNotificationCenter.current().removeAllDeliveredNotifications()
    }
}

3. Key Notes About Lifecycle Methods

  • When do these methods get called? applicationWillTerminate/sceneWillTerminate fire when the app is fully terminated—like when a user swipes it away from the multitask interface, or when the system kills it due to low memory. They won’t trigger if the app is just sent to the background (e.g., user presses the Home button).
  • Synchronous execution: The removeAllPendingNotificationRequests() method is lightweight enough that it’ll complete before the app terminates. If you want to confirm the cleanup for debugging, you can fetch pending requests first:
    UNUserNotificationCenter.current().getPendingNotificationRequests { pendingRequests in
        print("Pending notifications before cleanup: \(pendingRequests.count)")
        UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
        // Re-check if needed
        UNUserNotificationCenter.current().getPendingNotificationRequests { updatedRequests in
            print("Pending notifications after cleanup: \(updatedRequests.count)")
        }
    }
    
  • Background cleanup (optional): If you want to clear notifications even when the app is sent to the background (not fully terminated), add the same cleanup code to applicationDidEnterBackground(_:) (AppDelegate) or sceneDidEnterBackground(_:) (SceneDelegate).

Testing It Out

To verify it works:

  1. Schedule a test notification (e.g., using UNMutableNotificationContent + UNCalendarNotificationTrigger set to 5 minutes from now).
  2. Run your app, then swipe it away from the multitask view.
  3. Check if the pending notification is gone by calling getPendingNotificationRequests in a debug session or print statement.

内容的提问来源于stack exchange,提问作者Seungjun

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 19:22:27