简体   繁体   English

单击应用程序图标时,推送通知应用程序内徽章图标未更新

[英]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; 我正确地在iPhone上的应用程序图标上获得了推送通知徽章; 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. 我希望即使在应用程序处于后台的情况下,也要更新应用程序内的标签,就像facebook应用程序在Notifications Globe图标上方具有图标的方式一样。

I'll show the relevant methods in the AppDelegate (omitting tokens, etc): 我将在AppDelegate中显示相关方法(省略令牌等):

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: ViewController中 ,我在viewDidAppear中调用方法,并使其在每次接收到推送通知时更新标签并将数字增加1:

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: 首先,由于您正在使用Parse,因此您不需要自己处理application.applicationIconBadgeNumber

//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. 另外,问题似乎是您在加载View Controller时没有更新按钮的标志。 You're only updating them when you receive a new notification AND the View Controller is visible. 您只有在收到新通知并且View Controller可见时才更新它们。 In short, try this on your View Controller: 简而言之,在您的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 . 最后但并非最不重要的一点是,每当收到远程通知时,就将其传递到AppDelegate中的 func handleRemoteNotifications(application: UIApplication, userInfo: NSDictionary) This in turn posts an NSNotification to objects that are listening to it. 反过来,这会将NSNotification到正在监听的对象。 However, there may or may not be a ViewController, because it might have been deallocated while the app was in the background. 但是,可能存在或可能没有ViewController,因为在应用程序处于后台时可能已将其释放。 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. 尝试将以上各行移至AppDelegatefunc handleRemoteNotifications(application: UIApplication, userInfo: NSDictionary)方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 推送通知-应用徽章图标 - Push Notification - App Badge Icon 推送通知徽章iphone上的错误的应用程序图标 - Wrong app icon on push notification badge iphone 通知到达时未显示应用程序图标徽章 - App icon badge not showing when notification arrives 本地通知中的“应用程序图标”标志是否会从“推送通知”有效载荷标志中被覆盖? - Does a App Icon badge from a local notification get overridden from a Push Notification payload badge? 检测应用程序是否通过单击应用程序图标或推送通知启动(当应用程序被用户强制终止时) - Detect if Application is launched by clicking app icon or by push notification (when app is force killed by user) 通过单击应用程序图标直接启动应用程序时,无法获取通知数据 - Push notification data not getting when app launched directly by clicking app icon 通过推送重置应用程序图标上的徽章 - Reset badge on app icon from push 是否可以在不通过iOS中的推送通知打开应用程序的情况下更新应用程序图标上的徽章编号? - Is it possible to update badge number on app icon without openining app on push notification in iOS? 当应用程序处于后台或应用程序中时,使用推送通知设置应用程序图标上的徽章 - Setting badge on app icon with push notifications when app is in background or app has been killed 应用更新时设置图标徽章 - Set icon badge when app updated
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM