Hallo boeken en tijdschriften, Leo hier. Today we will talk about Programmatically add app icon badge in SwiftUI.

I was vacationing for the last two weeks. I went to a lot of places here and also in France.

In France, my wife and family went to Disneyland while I was taking care of my wife’s grandma in the Airbnb because she got some flu. It’s life. On that day I watched two very interesting documentaries that were sitting in my backlog for a long time, “Trainwreck: Woodstock ’99” and “Pepsi, where’s My Jet”. And man… That’s why I love documentaries, the things that you can learn from watching those are really interesting.

The Woodstock 99 documentary was about a group of people that tried to reproduce the legendary Woodstock music festival but failed miserably. The premise was good, but the implementation was a disaster. All the base concepts of “love and peace” from the first Woodstock were replaced by what was selling the most at the time, and at that time what was selling most was “Angry” music. So they gathered, 250k angry people for 3 days… What could go wrong?

The Pepsi documentary is a really funny premise. One day Pepsi made a very innocent commercial telling people that if they accumulate 7 million Pepsi coins ( that you could get through drinking Pepsi) they could win a Harrier II Jet. Well, a guy did that by not drinking 7 million Pepsi cans but using an option where he could buy Pepsi points for 0.1 cents a point. So he could get the 32 million dollar jet for 700k, pretty good deal huh? That was an amazing story about David and Golias, with a lot of plot twists in the middle.

In case you missed it, last week I talked about a topic that is very important for iOS developers that is cyclomatic complexity, check here to learn what is it and how to avoid it in your code base.

Let’s stop bumbling and start coding but first…

 

Painting of The Day

I chose the artwork called Self-Portrait with Badges create in 1961 by Peter Blake

Blake’s selfie is a cool mix of old-school vibes and modern pop culture. He might’ve gotten inspired by Gainsborough’s well-known portrait, The Blue Boy. But, instead of silk, Blake rocked denim, which was super trendy among American youngsters back then.

His love for American pop culture is also clear from his choice of baseball shoes, funky badges, and an Elvis Presley mag, which was just blowing up in the UK. Just like a traditional portrait artist, Blake used these objects to show off his interests and accomplishments.

I chose this because we will talk about badges today and this man has a lot of them.

 

Problem – App Badges in SwiftUI

You want to Programmatically add app icon badges to your app.

The feature that we will implement today is this:

 how to add app icon badge in Swift iOS. This image depicts an app icon with a red badge in the top.

There are several ways to achieve this. Today we will dive into the programmatic one.

 

How to Change the App Icon Badge Programatically in SwiftUI?

To be able to see the badges we need to follow these steps: 

  1. Ask for the user’s permission to use the app badge alert in the notification center.
  2. Increase the applicationIconBadgeNumber in the UIApplication object.

 

Just that, simple isn’t it?

Example of Setting the App Icon Badge in SwiftUI

Create a new SwiftUI project. Then create a file called AppAlertBadgeManager.swift and copy and paste the code below: 

import SwiftUI

protocol BadgeNumberProvidable: AnyObject {
    var applicationIconBadgeNumber: Int { get set }
}

extension UIApplication: BadgeNumberProvidable {}

actor AppAlertBadgeManager {
    
    let application: BadgeNumberProvidable
    
    init(application: BadgeNumberProvidable) {
        self.application = application
    }
    
    @MainActor
    func setAlertBadge(number: Int) {
        application.applicationIconBadgeNumber = number
    }
    
    @MainActor
    func resetAlertBadgetNumber() {
        application.applicationIconBadgeNumber = 0
    }
}

Why we created a protocol for that? Because we want to cover our code with unit tests, and the easiest way is to not make our classes depend on concrete implementation, it is better to depend on abstractions that in this case a protocol.

In the code above we are setting the app icon badge using an actor, and if you are interested in why we are using the actor just check this article. This is important to avoid most (not all) racing conditions and it is always good to prevent those.

This actor has only two functions one adding the desired badge number and one completely removing the badge number.

Now to test the badge number just add it to your ContentView.swift and ask for user permission:

import SwiftUI

struct ContentView: View {
    
    @State var badgeManager = AppAlertBadgeManager(application: UIApplication.shared)

    var body: some View {
        VStack {
            Button("Set Badge Number") {
                badgeManager.setAlertBadge(number: 1) // Adding the badge app icon
            }
            .buttonStyle(.borderedProminent)
            
            Button("Reset Badge Number") {
                badgeManager.resetAlertBadgetNumber() // removing badge app icon
            }
            .buttonStyle(.borderedProminent)
            .tint(.red)
        }
        .onAppear {
            
            UNUserNotificationCenter.current().requestAuthorization(options: .badge) // Mark 1
                 { (_, _) in }
        }
        .padding()
        
    }
}

In Mark 1 we are asking the user permission to use app icon badges. I think this is one of the greatest things from Apple, the user experience is above all things, we as iOS developers can’t do little without User Permission, and putting alerts on the home screen is one of those.

 

Another Way to Add App Icon Badge on iOS

You can send a remote push notification to the user’s device with a badge count included. To do this, you need to configure your app for remote notifications and use your server to send the notification payload.

The payload should include a “badge” key with an integer value representing the desired badge count.

Here’s an example of a JSON payload with a badge count:

{
    "aps": {
        "alert": "You have 5 new messages",
        "badge": 5
    }
}

 

Interview Questions about App Icon Badges in iOS

I’m liking doing this interview questions section, if anyone has feedback just reach out on Twitter/LinkedIn.

 

How do I request permission to show badge numbers on the app icon?

A: To request permission for showing badge numbers, you need to use the UserNotifications framework. Request authorization for the badge by passing the .badge option in the requestAuthorization method.

 

Q: How do I reset or clear the app icon badge number?

A: To reset the app icon badge number to zero, you can set the applicationIconBadgeNumber property of the UIApplication shared instance to 0:

 
func clearBadgeCount() { UIApplication.shared.applicationIconBadgeNumber = 0 }

 

Q: Can I show a badge on a specific tab of a UITabBarController?

A: Yes, you can show a badge on a specific tab by setting the badgeValue property of the corresponding UITabBarItem. For example, to set a badge value of “3” on the first tab:

tabBarController?.tabBar.items?[0].badgeValue = "3"

Q: Can I customize the appearance of the app icon badge?

A: Unfortunately, iOS does not provide direct public customization options for the app icon badge appearance. However, you can create custom badges within your app’s user interface, such as on table cells, collection view cells, or other UI elements. And you can use private APIs to do that, but I wouldn’t recommend.

 

How can I update the app icon badge number based on the number of unread messages or notifications?

A: You can maintain the count of unread messages or notifications on your app’s backend, or locally on the device, depending on your app’s architecture. Whenever the count is updated, use one of the methods mentioned earlier in this conversation to update the app icon badge number.

Remember to always request permission from users before using badge notifications, and use them responsibly to avoid creating unnecessary distractions or anxiety.

And that’s it for today!

 

Summary – A Guide to App Icon Badge in SwiftUI

In conclusion, this article has demonstrated how to programmatically add app icon badges in SwiftUI using different methods.

We covered how to set and reset the badge numbers, as well as how to request user permissions to display badges. We also discussed alternative ways to add app icon badges, such as through remote push notifications.

Finally, we touched on some common questions related to app icon badges and their usage in iOS development.

App icon badges can be a valuable tool in enhancing the user experience when implemented responsibly, keeping user permissions and potential distractions in mind. By understanding the various ways to integrate app icon badges into your iOS app, you’ll be better equipped to create a more engaging and informative experience for your users.

Fellow Apple Developers, that’s all.

I hope you liked reading this article as much as I enjoyed writing it. If you want to support this blog you can Buy Me a Coffee or say hello on Twitter. I’m available on LinkedIn or send me an e-mail through the contact page.

You can likewise sponsor this blog so I can get my blog free of ad networks.

Thanks for the reading and… That’s all folks.

Image credit: Featured Painting