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

时间:2018-12-11 10:17:31

标签: swift push-notification uibutton message badge

我有社交网络应用。应用程序图标徽章和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 个答案:

答案 0 :(得分:0)

我有这个助手:

//
//  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
    }
}

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

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

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