简体   繁体   中英

Push notification in-app badge icon not updating when clicking on app icon

I am having a bit of trouble getting an in-app badge icon label to be updated correctly. I want something that does this:

This red icon appears anytime a push notification is received. I get the push notification badge on the app icon on the iPhone correctly; however, this red icon inside the app only appears if I press on the banner for the push notification, OR if I'm already inside the app.

My problem is that it does not appear if I press on the actual app icon. I'd like for the label within the app to be updated even when the app is in the background kind of like how the facebook app has icons on top of the notifications globe icon.

I'll show the relevant methods in the AppDelegate (omitting tokens, etc):

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

    let userInfo: AnyObject? = launchOptions?[UIApplicationLaunchOptionsRemoteNotificationKey]
    if userInfo != nil {
        handleRemoteNotifications(application, userInfo: userInfo! as! NSDictionary)
        return true
    }

    if application.applicationState != UIApplicationState.Background {
        let oldPushHandlerOnly = !self.respondsToSelector(Selector("application:didReceiveRemoteNotification:fetchCompletionHandler:"))
        let noPushPayload: AnyObject? = launchOptions?[UIApplicationLaunchOptionsRemoteNotificationKey]
        if oldPushHandlerOnly || noPushPayload != nil {
            PFAnalytics.trackAppOpenedWithLaunchOptionsInBackground(launchOptions, block: nil)             
        }
    }

    return true
}

func handleRemoteNotifications(application: UIApplication, userInfo: NSDictionary) {
    if let type: String = userInfo["type"] as? String {
        switch (type) {
        case "follow":
            NSNotificationCenter.defaultCenter().postNotificationName("commentNotification", object: self)
        case "comment":
            NSNotificationCenter.defaultCenter().postNotificationName("commentNotification", object: self)
        default:
            return
        }
    }
}

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

    let installation = PFInstallation.currentInstallation()
    if installation.badge != 0 {
        installation.badge = 0
        installation.saveEventually()
    }
}

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler handler: (UIBackgroundFetchResult) -> Void) {
    if let badgeNumber: Int = userInfo["badge"] as? Int {
        application.applicationIconBadgeNumber = badgeNumber
    }

    handleRemoteNotifications(application, userInfo: userInfo)

    if application.applicationState == .Inactive {
        PFAnalytics.trackAppOpenedWithRemoteNotificationPayloadInBackground(userInfo, block: nil)
    }

    handler(.NewData)
}

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
    if application.applicationState == .Inactive  {
        // The application was just brought from the background to the foreground,
        // so we consider the app as having been "opened by a push notification."
        PFAnalytics.trackAppOpenedWithRemoteNotificationPayloadInBackground(userInfo, block: nil)
        handleRemoteNotifications(application, userInfo: userInfo)
    }
}

In the ViewController , I am calling the methods in viewDidAppear and making it update the label and increase the number by 1 each time a push notification is received:

override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated)

    followLabelNumber = NSUserDefaults.standardUserDefaults().integerForKey("followNumberKey")
    commentLabelNumber = NSUserDefaults.standardUserDefaults().integerForKey("commentNumberKey")

    NSNotificationCenter.defaultCenter().removeObserver(self, name: "followNotification", object: nil)
    NSNotificationCenter.defaultCenter().addObserver(self, selector:"followNotificationReceived:", name:"followNotification", object: nil)
    NSNotificationCenter.defaultCenter().removeObserver(self, name: "commentNotification", object: nil)
    NSNotificationCenter.defaultCenter().addObserver(self, selector:"commentNotificationReceived:", name:"commentNotification", object: nil)


    self.navigationController?.navigationBarHidden = true
}

func makeIncrementer(forIncrement amount: Int) -> () -> Int {
    var runningTotal = 0
    func incrementer() -> Int {
        runningTotal += amount
        return runningTotal
    }
    return incrementer
}

func followNotificationReceived(notification: NSNotification) {
    if let number = followLabelNumber {
        let aNumber = makeIncrementer(forIncrement: 1)
        followLabelNumber = number + aNumber()
        NSUserDefaults.standardUserDefaults().setInteger(followLabelNumber!, forKey: "followNumberKey")
        NSUserDefaults.standardUserDefaults().synchronize()
        profileNotificationLabel.hidden = false
        profileNotificationLabel.text = String(followLabelNumber!)
        hasReceivedFollowNotification = true
    }
}

func commentNotificationReceived(notification: NSNotification) {
    if let number = commentLabelNumber {
        let aNumber = makeIncrementer(forIncrement: 1)
        commentLabelNumber = number + aNumber()
        NSUserDefaults.standardUserDefaults().setInteger(commentLabelNumber!, forKey: "commentNumberKey")
        NSUserDefaults.standardUserDefaults().synchronize()
        commentsNotificationLabel.hidden = false
        commentsNotificationLabel.text = String(commentLabelNumber!)
        hasReceivedCommentNotification = true
    }
}

deinit {
    NSNotificationCenter.defaultCenter().removeObserver(self)
}

I'd greatly appreciate anyone's help as I've been stuck on this for a few days now.

EDIT: changed title

Firstly, you shouldn't need to handle application.applicationIconBadgeNumber yourself since you're using Parse:

//You don't need these...
if (application.applicationIconBadgeNumber != 0) {
    application.applicationIconBadgeNumber = 0
}

//Because these lines will set the application's icon badge to zero
let installation = PFInstallation.currentInstallation()
if installation.badge != 0 {
    installation.badge = 0
    installation.saveEventually()
}

You don't need this as well:

//Because Parse handles that for you
if let badgeNumber: Int = userInfo["badge"] as? Int {
    application.applicationIconBadgeNumber = badgeNumber
}

Also, the problem seems to be that you're not updating the button's badge when your View Controller loads. You're only updating them when you receive a new notification AND the View Controller is visible. In short, try this on your View Controller:

override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated)

    followLabelNumber = NSUserDefaults.standardUserDefaults().integerForKey("followNumberKey")
    commentLabelNumber = NSUserDefaults.standardUserDefaults().integerForKey("commentNumberKey")

    //BEGIN SUGGESTED CODE
    profileNotificationLabel.hidden = followLabelNumber > 0
    profileNotificationLabel.text = String(followLabelNumber!)

    commentsNotificationLabel.hidden = commentLabelNumber > 0
    commentsNotificationLabel.text = String(commentLabelNumber!)
    //END SUGGESTED CODE

    NSNotificationCenter.defaultCenter().removeObserver(self, name: "followNotification", object: nil)
    NSNotificationCenter.defaultCenter().addObserver(self, selector:"followNotificationReceived:", name:"followNotification", object: nil)
    NSNotificationCenter.defaultCenter().removeObserver(self, name: "commentNotification", object: nil)
    NSNotificationCenter.defaultCenter().addObserver(self, selector:"commentNotificationReceived:", name:"commentNotification", object: nil)


    self.navigationController?.navigationBarHidden = true
}

Last, but definitely not least, whenever you receive a remote notification, you're passing it to func handleRemoteNotifications(application: UIApplication, userInfo: NSDictionary) inside your AppDelegate . This in turn posts an NSNotification to objects that are listening to it. However, there may or may not be a ViewController, because it might have been deallocated while the app was in the background. Thus, these lines of code never get called when you receive a remote notification:

NSUserDefaults.standardUserDefaults().setInteger(followLabelNumber!, forKey: "followNumberKey")
NSUserDefaults.standardUserDefaults().synchronize()

Try moving the lines above to your AppDelegate 's func handleRemoteNotifications(application: UIApplication, userInfo: NSDictionary) method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM