快速移除推送通知徽章编号? ?

我试图删除图标徽章在迅速,但 PFInstallationsdo 不似乎工作了。我该怎么做?

63058 次浏览

You can "remove" the app badge icon by setting it to 0:

Swift < 3.0

UIApplication.sharedApplication().applicationIconBadgeNumber = 0

Swift 3.0+

UIApplication.shared.applicationIconBadgeNumber = 0

This question shows when you can use it: How to clear push notification badge count in iOS?

Swift 4.2

At the AppDelegate, just put this code:

    func applicationDidBecomeActive(_ application: UIApplication) {
application.applicationIconBadgeNumber = 0
}

Swift 5

At the AppDelegate didFinishLaunchingWithOptions

UIApplication.shared.applicationIconBadgeNumber = 0

Swift 5

While you can put this in the AppDelegate didFinishLaunchingWithOptions, this will not clear the badge if the app is inactive and has moved to active.

If you wish to clear the badge regardless of the previous state you need to put this in the SceneDelegate instead of the AppDelegate.

func sceneDidBecomeActive(_ scene: UIScene) {
UIApplication.shared.applicationIconBadgeNumber = 0
}

A more SwiftUI-oriented approach might be to listen for changes in the @Environment(\.scenePhase) var scenePhase in the root view. Then, if the new phase is .active, set UIApplication.shared.applicationIconBadgeNumber to 0 as discussed by the other answers.

Example Code:

@main
struct MRPApp: App {
@Environment(\.scenePhase) var scenePhase
@UIApplicationDelegateAdaptor(AppDelegate.self) var delegate
var body: some Scene {
WindowGroup {
ContentView()
.onChange(of: scenePhase) { newPhase in
if newPhase == .active {
UIApplication.shared.applicationIconBadgeNumber = 0
}
}
}
}
}