1

当应用程序终止时,我想将 iOS 应用程序图标徽章设置为零(这会删除图标上的徽章)。(...使用 Swift 4、iOS 10.x、11.x)

在我的 ViewController 中,我成功地请求了这样的本地通知:

@objc func requestLocalNotification() -> Bool {
    let center = UNUserNotificationCenter.current()
    var result = true

    center.requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
        if granted {
            result = true
        } else {
            result = false
        }
    }

    return result
}

我成功地设置了应用程序图标徽章:

@objc func notifyBadge(_ badge: Int) {
    let content = UNMutableNotificationContent()
    content.badge = badge as NSNumber

    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false)

    let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)

    UNUserNotificationCenter.current().add(request)
}

当应用程序在 AppDelegate.swift 中以此启动时,我可以删除徽章:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    application.applicationIconBadgeNumber = 0

    return true
}

当用户双击主页按钮时,在这里尝试这样做似乎很有意义:

func applicationWillTerminate(_ application: UIApplication) {

    application.applicationIconBadgeNumber = 0
}

但它不起作用。

我尝试使用共享应用程序对象而不是传递的应用程序参数:

UIApplication.shared.applicationIconBadgeNumber = 0

SO上有类似的问题(和答案)来重置应用程序图标徽章,但我只发现1个与用户终止应用程序有关的问题:

iphone如何捕捉应用程序是否终止以更新徽章图标

但是这个问题已经超过 5 年了,实际上并没有得到解决方案的回答。也许从那时起有人想出了一个办法?

4

0 回答 0