簡體   English   中英

如何在 iOS 推送通知上增加徽章

[英]How to do badge increment on iOS push notification

我目前正在從有效載荷中獲取徽章。 但是我怎樣才能更新那個值。

{"aps":
    {"alert":"Notification Hub test notification2",
     "badge":1,
     "sound":"Default"}
}

當我發送它時,它總是在徽章編號中顯示 1,但是當我進入應用程序並退出時,它正在更新。正因為如此,

func applicationDidBecomeActive(application: UIApplication) {
        UIApplication.sharedApplication().applicationIconBadgeNumber = UIApplication.sharedApplication().applicationIconBadgeNumber + 1
    }

但是當我發送新的推送通知時,它再次在圖標中顯示 1 作為徽章編號。 我應該怎么做,據我了解,我應該在發送有效負載時發送更新的徽章。 為此,我必須處理后端。

除此以外還有什么建議可以在應用程序內部處理嗎?

如果您的項目有通知擴展,您可以在其中進行標記設置。

首先,啟用 App Groups 並從UserDefaults中的應用通知服務擴展中保存您的徽章計數。 我們正在使用應用程序組,因為我們需要在打開應用程序時從AppDelegate清除徽章計數。 您還可以從通知服務擴展中將徽章的值設置為bestAttemptContent.badge

在通知服務擴展中:

if let userDefaults = UserDefaults(suiteName: "group.com.bundle.appname") {
    
    let badgeCount = userDefaults.integer(forKey: "badgeCount")
    if badgeCount > 0 {
        userDefaults.set(badgeCount + 1, forKey: "badgeCount")
        bestAttemptContent.badge = badgeCount + 1 as NSNumber
    } else {
        
        userDefaults.set(1, forKey: "badgeCount")
        bestAttemptContent.badge = 1
    }
}

在 AppDelegate 中,您可以清除徽章...並在 userdefaults 上將徽章的值設置為零

if let userDefaults = UserDefaults(suiteName: "group.com.bundle.appname") {
    userDefaults.set(0, forKey:"badgeCount") // "change "badgecount" to be "badgeCount"
}
UIApplication.shared.applicationIconBadgeNumber = 0

我會給你我的方式:

我的計划是使用 KVO 來監聽[UIApplication sharedApplication].applicationIconBadgeNumber

- (void)setupBadgeOperation {
    [[UIApplication sharedApplication] addObserver:self forKeyPath:@"applicationIconBadgeNumber" options:NSKeyValueObservingOptionNew context:nil];
}

一旦值更改,我使用[[NSNotificationCenter defaultCenter] postNotificationName:STATUS_BADGENUMBER_CHANGED object:nil]通知 UI 需要修改哪些位置以更改徽章。

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *, id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"applicationIconBadgeNumber"]) {
        [[NSNotificationCenter defaultCenter] postNotificationName:STATUS_BADGENUMBER_CHANGED object:nil];
    }
}

接收遠程通知以更改[UIApplication sharedApplication].applicationIconBadgeNumber的三種情況。

一個。 應用程序是前台
灣。 應用程序是背景
C。 應用程序未啟動

在 a 和 b 情況下,將調用此方法:

- (void)application:(UIApplication *)application
    didReceiveRemoteNotification:(NSDictionary *)userInfo
          fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    void(^tapBlock)(void(^completeHandler)()) = ^(void(^completeHandler)()) { 
    // here I remove some code not related with the question
    NSNumber *badgeNumber = userInfo[@"aps"][@"badge"];
    [UIApplication sharedApplication].applicationIconBadgeNumber = badgeNumber.integerValue;
} 

在c的情況下,沒有辦法獲取回調,所以我將手動進行。

- (void)applicationDidBecomeActive:(UIApplication *)application {
    [[NSNotificationCenter defaultCenter] postNotificationName:STATUS_BADGENUMBER_CHANGED object:nil];
}

就是這樣,對我來說效果很好。

這是我的方式斯威夫特:

1) 啟動應用程序后,您需要在 Firebase Realtime 數據庫中設置徽章(您可以隨意調用它的變量)為零。 加上設置 application.applicationIconBadgeNumber = 0。這是我在 AppDelegate 中的操作方式:

func applicationDidBecomeActive(_ application: UIApplication) {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    application.applicationIconBadgeNumber = 0

    // Reset badge number to zero
    let userID = Auth.auth().currentUser?.uid

    let dbRef = Database.database().reference()
    dbRef.child("Users Info").child(userID!).updateChildValues(["badge":"0"], withCompletionBlock: { (err, ref) in
        if err != nil {
            print(err!)
            return
        }
    })

}

2) 轉到觸發函數的 index.js。

...
return admin.database().ref('/Users Info/' + owner).once('value', snapshot => {

    var ownerValue = snapshot.val();

    var badgeNumber = parseInt(ownerValue.badge) + 1;

    // Notification details.
    const payload = {
      notification: {
        title: 'You have a new request!',
        body: `A new request from ${downedBy.name}.`,
        badge:`${badgeNumber}`,
        sound: 'default',
      }
    };
    ...
    ...
    // Upload the new value of badge into Firebase to keep track of the number
    return admin.database().ref('/Users Info/' + owner).update({badge:badgeNumber});
    ...
    })

首先,讓您的服務器人員向您發送更新的徽章計數器。 你的工作只是展示它,而不是最終維護它。

您需要在applicationDidReceiveRemoteNotifications Delegate 方法中執行更新操作,如下所示:

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]){
       let notification = userInfo["aps"] as? NSDictionary
       let badge = (notification["badge"] as String).toInt() 
       UIApplication.sharedApplication().applicationIconBadgeNumber = UIApplication.sharedApplication().applicationIconBadgeNumber + badge;

}

在您的DidBecomeActive方法中:

func applicationDidBecomeActive(application: UIApplication) {
       if(UIApplication.sharedApplication().applicationIconBadgeNumber!=0){
    UIApplication.sharedApplication().applicationIconBadgeNumber = 0
    }

這是假設您的服務器向您發送更新的推送徽章計數器。 中,我會做這樣的事情來向服務器傳達推送計數器現在必須設置為零:

var currentInstallation = PFInstallation.currentInstallation()
      if currentInstallation.badge != 0 {
        currentInstallation.badge = 0
        currentInstallation.save
       }

如果我不這樣做,服務器將假定 Push 尚未被讀取,並會在下一次推送時在其末端增加標記計數器,依此類推。

將您的徽章計數保留在 NSUserDefault 中以獲得最大可用性。 即使您重新啟動設備,您也可以從 NSUserDefault 獲取徽章計數。

當您獲得另一個有效負載時,您可以在 NSUserDefault 中繼續增加徽章計數。

服務器必須在@"badge"鍵中增加很多計數。 當您打開應用程序時,您需要向服務器發送請求 - 重置推送計數器(徽章)。 applicationDidBecomeActive方法中。

{"aps":
    {"alert":"Notification Hub test notification2",
     "badge":20,
     "sound":"Default"}
}

每當我們使用推送通知時。 我們必須更新它的徽章數量。 否則每次徽章都是一樣的。 例如,如果您收到通知,其計數為 1,並且您閱讀了它,它仍會顯示徽章 1。因此,您必須清除徽章。 通過使用這樣的代碼,

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

處理徽章的最佳解決方案是使用您可以創建的通知擴展。 通知擴展,還使用 ​​KVO 更新應用程序中的徽章。 和應用程序組,用於保存徽章數量並在應用程序中管理。 當您收到通知時,您可以閱讀您有多少通知並將通知徽章添加到該通知並更新您的通知

guard let content = (request.content.mutableCopy() as? UNMutableNotificationContent) else {
        contentHandler(request.content)
        return
    }

    if let badge = bestAttemptContent?.badge as? Int {
        let newBadge = badge + NotificationManangerBridge.shared.getTotalBadge()
        content.badge = NSNumber(value: newBadge)
        NotificationManangerBridge.shared.updateTotalBadge(badgeCount: newBadge)

    } else {
        content.badge = 0
    }
    guard let notification = bestAttemptContent?.copy() as? UNNotificationContent else { return }
    contentHandler(notification)

你正朝着正確的方向前進。 您必須從有效負載中更新徽章編號,這是推送通知的標准方式。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM