收到消息时将徽章添加到聊天按钮

Posted

技术标签:

【中文标题】收到消息时将徽章添加到聊天按钮【英文标题】:Adding badge to chat button when got message 【发布时间】:2018-12-11 10:17:31 【问题描述】:

我有社交网络应用程序。应用程序图标徽章和 tabbar.item 徽章工作正常。但我在主页上有一个消息按钮,就像 instagram 一样。我希望此按钮在收到新消息时显示徽章。这是我的收件箱推送通知功能

// Send Push notification
        let pushStr = "\(PFUser.current()![USER_USERNAME]!) sent you a message.:\nRelated post: \(self.adObj[ADS_TITLE]!)"
        //\(self.lastMessageStr)

        let data = [ "badge" : "Increment",
                     "alert" : pushStr,
                     "sound" : "bingbong.aiff"
        ]
        let request = [
                    "someKey" : self.userObj.objectId!,
                    "data" : data
        ] as [String : Any]
        PFCloud.callFunction(inBackground: "push", withParameters: request as [String : Any], block:  (results, error) in
            if error == nil 
                print ("\nPUSH SENT TO: \(self.userObj[USER_USERNAME]!)\nMESSAGE: \(pushStr)\n")
             else 
                print ("\(error!.localizedDescription)")
            
        )

这是我在主页视图控制器中的聊天按钮

    @IBAction func chatsButt(_ sender: Any) 
    if PFUser.current() != nil  
        let aVC = storyboard?.instantiateViewController(withIdentifier: "Chats") as! Chats
        navigationController?.pushViewController(aVC, animated: true)
     else 
        showLoginAlert("You need to be logged in to see your Chats. Want to Login now?")
    

收到新消息时,只有消息按钮应该显示徽章, 但是当得到新的喜欢时,只有标签栏项目应该显示徽章。我该怎么做?

【问题讨论】:

【参考方案1】:

我有这个助手:

//
//  UIButton+BadgeCircle.swift
//
//  Created by João Marcelo Ferreira Pinho on 27/08/18.
//  Copyright © 2018 WIT Software. All rights reserved.
//
// source: https://gist.github.com/freedom27/c709923b163e26405f62b799437243f4

import UIKit

fileprivate struct Badge 
    static let size: CGSize = CGSize(width: 16, height: 16)
    static let offSet: CGFloat = 8
    static let fontSize: CGFloat = 11.0
    static let color: UIColor = .black
    static let filled: Bool = true


private var handle: UInt8 = 0

extension UIButton 

    private var badgeLayer: CAShapeLayer? 
        if let badge: AnyObject = objc_getAssociatedObject(self, &handle) as AnyObject? 
            return badge as? CAShapeLayer
         else 
            return nil
        
    

    func addBadge(number: Int, withColor color: UIColor = Badge.color, filled: Bool = Badge.filled) 
        badgeLayer?.removeFromSuperlayer()

        let badge = CAShapeLayer()
        let location = CGPoint(x: frame.width - Badge.offSet, y: -Badge.offSet)
        badge.drawCircleAt(location, withColor: color, filled: filled)
        layer.addSublayer(badge)

        let label = CATextLayer()
        label.string = "\(number)"
        label.alignmentMode = kCAAlignmentCenter
        label.fontSize = Badge.fontSize
        label.frame = CGRect(origin: CGPoint(x: location.x, y: -6.5), size: Badge.size)
        label.foregroundColor = filled ? UIColor.white.cgColor : color.cgColor
        label.backgroundColor = UIColor.clear.cgColor
        label.contentsScale = UIScreen.main.scale
        badge.addSublayer(label)

        // Save Badge as UIButton property
        objc_setAssociatedObject(self, &handle, badge, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
    

    func removeBadge() 
        badgeLayer?.removeFromSuperlayer()
    


private extension CAShapeLayer 

    func drawCircleAt(_ location: CGPoint, withColor color: UIColor, filled: Bool) 
        fillColor = filled ? color.cgColor : UIColor.white.cgColor
        strokeColor = color.cgColor
        path = UIBezierPath(ovalIn: CGRect(origin: location, size: Badge.size)).cgPath
    

将此代码粘贴到一个swift文件中,然后您可以简单地调用button.addBadge(number: 2)并绘制一个自定义徽章。

您可以使用 fileprivate struct Badge 自定义您的徽章,这些是我的项目主题的默认值,您的可以不同。

在 cmets 类中,您可以找到我的代码所基于的位置(来源:https://gist.github.com/freedom27/c709923b163e26405f62b799437243f4)。

【讨论】:

感谢Pincha的帮助,其实我想要的是;收到新消息时,只有消息按钮显示徽章,但收到新消息时,只有标签栏项目显示徽章。我该怎么做?

以上是关于收到消息时将徽章添加到聊天按钮的主要内容,如果未能解决你的问题,请参考以下文章

Twilio 可编程聊天 — 使应用程序徽章与未读消息计数保持同步

关于Java聊天收到消息自动弹出窗口代码

在 Swift 中收到推送时添加徽章

从 Quickblox 对话框中删除特定聊天消息

将收到的 Facebook 消息(聊天 + 消息)转发到我的电子邮件收件箱,然后从我的 Facebook 收件箱中删除它们

如何从 GTalk 客户端接收聊天消息