如何在应用终止时删除iOS应用图标徽章?

时间:2018-01-06 04:11:44

标签: ios swift badge usernotifications

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

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

@echo off
setlocal EnableDelayedExpansion

set "x=cheese"
set "y=Louise"

for %%f in (*%x%*.txt) do (
    echo %%f
    set "name=%%f"
    ren "%%f" "!name:%x%=%y%!"
)
dir *.txt /b

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

@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
}

我可以在应用程序以AppDelegate.swift:

开头时删除徽章
@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)
}

当用户双击主页按钮时,尝试在此处进行操作似乎是有意义的:

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

    application.applicationIconBadgeNumber = 0

    return true
}

但它不起作用。

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

func applicationWillTerminate(_ application: UIApplication) {

    application.applicationIconBadgeNumber = 0
}

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

iphone how to catch if the app is terminated to update the badge icon

但是这个问题已经超过5年了,并没有真正解决问题。也许从那以后有人找到了办法吗?

0 个答案:

没有答案
相关问题