0

I've got social network app. App icon badge and tabbar.item badge work fine. But I have a message button in homepage just like instagram. I want this button to show badge when got new message. Here is my Inbox push notification function

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

Here is my chat button in homepageviewcontroller

    @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?")
    }
}

When got new message, only message button should show badge, But when got new like, only tab bar item should show badge. How can I do that ?

1 Answers1

0

I had this helper:

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

Paste this code in a swift file, then you can simple call button.addBadge(number: 2) and will draw a custom badge.

You can customize your Badge with the fileprivate struct Badge, those were my default values for my project theme, yours can be different.

In class comments you can find where my code is based on (source: https://gist.github.com/freedom27/c709923b163e26405f62b799437243f4).

Pincha
  • 93
  • 1
  • 10
  • Thanks for your help Pincha, actually what I want is; When got new message, only message button shows badge, But when got new like, only tab bar item shows badge. How can I do that ? – Uchiha Sasuke Dec 12 '18 at 10:03