我正在后台模式下下载我的事件,因为我会收到推送和静音通知。因为当我的应用程序处于后台模式时我必须下载数据,所以我使用静默通知通过 Web 服务下载数据,在此之前我applicationIconBadgeNumber
根据增量值进行更新。当我使用自动增加的值更新 applicationIconBadgeNumber 时,我的所有推送通知都在通知中心被清除。如果我没有设置任何 applicationIconBadgeNumber,它们将保持不变。正如我在下面发布的代码一样,如果我遗漏了什么,请告诉我。
var autoIncrementForNotification:Int = 0
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
UIApplication.shared.setMinimumBackgroundFetchInterval(60)
if #available(iOS 10, *) {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) {(accepted, error) in
if !accepted {
print("Notification access denied.")
} else {
application.registerForRemoteNotifications()
}
}
} else {
application.registerForRemoteNotifications(matching: [.badge, .sound, .alert])
}
return true
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
UserDefaults.standard.removeObject(forKey: "Device_Token")
UserDefaults.standard.setValue(deviceTokenString, forKey: "Device_Token")
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Swift.Void){
let aps = userInfo["aps"] as! [String: AnyObject]
if ((aps["content-available"] as? NSString)?.integerValue == 1)
{
let type = (aps["type"] as? NSString)
if(type == Constants.action_type_Events)
{
if (application.applicationState == .inactive || application.applicationState == .background)
{
autoIncrementForNotification += 1
application.applicationIconBadgeNumber = autoIncrementForNotification
// Firing my Web service
completionHandler(UIBackgroundFetchResult.newData)
}
}
}
}
func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void){
completionHandler(UIBackgroundFetchResult.newData)
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("i am not available in simulator \(error)")
}
func applicationDidBecomeActive(_ application: UIApplication) {
application.applicationIconBadgeNumber = 0
autoIncrementForNotification = 0
}