PeteSE4
PeteSE4

Reputation: 433

Changing Badge Notification count with Pushy in Capacitor/Cordova on iOS

I have a Capacitor/Cordova app using Pushy (https://pushy.me) to handle push notifications. Sending push notifications to devices seems to work fine, and as part of that transaction I can set the app's notification count on the icon when the app is closed.

However, Pushy only seems to have an JS option to clear the counter Pushy.clearBadge(); rather than change it to a specific number from within the app when it's running. The scenario being if a user has read one message, but leaves two unread and then closes the app, I want the counter to be correct.

Digging through the PushyPlugin.swift code, the function for Pushy.clearBadge(); looks like this:

@objc(clearBadge:)
func clearBadge(command: CDVInvokedUrlCommand) {
    // Clear app badge
    UIApplication.shared.applicationIconBadgeNumber = 0;
    
    // Always success
    self.commandDelegate!.send(
        CDVPluginResult(
            status: CDVCommandStatus_OK
        ),
        callbackId: command.callbackId
    )
}

Which is tantalisingly close to giving me what I need, if only I could pass an integer other than zero in that line UIApplication.shared.applicationIconBadgeNumber = 0;

My knowledge of Swift is zilch, other than recognising familiar programming syntax. I thought I'd have a hack at it and tried adding this to the PushyPlugin.swift file:

@objc(setBadge:)
func setBadge(command: CDVInvokedUrlCommand) {
    // Clear app badge
    UIApplication.shared.applicationIconBadgeNumber = 100;
    
    // Always success
    self.commandDelegate!.send(
        CDVPluginResult(
            status: CDVCommandStatus_OK
        ),
        callbackId: command.callbackId
    )
}

But the app coughed up Pushy.setBadge is not a function when I tried to give that a spin (note, I was testing with 100 just to see what would happen, ideally I'd want to pass an integer to that newly hacked in function).

So what I've learnt so far is I know nothing about Swift.

Am I sort of on the right lines with this, or is there a better way to set the badge counter?

Upvotes: 0

Views: 917

Answers (1)

PeteSE4
PeteSE4

Reputation: 433

Ok, so I spotted in the pushy-cordova/www folder a Pushy.js file which I needed to add my new function to

{
    name: 'setBadge',
    noError: true,
    noCallback: true,
    platforms: ['ios']
},

Then, a bit of trial and error with the PushyPlugin.swift function I added to this:

@objc(setBadge:)
func setBadge(command: CDVInvokedUrlCommand) {
    
    UIApplication.shared.applicationIconBadgeNumber = command.arguments[0] as! Int;
    
    // Always success
    self.commandDelegate!.send(
        CDVPluginResult(
            status: CDVCommandStatus_OK
        ),
        callbackId: command.callbackId
    )
}

Then this can be called in my Capacitor project with Pushy.setBadge(X); (X being the int value you want to display on your icon).

Upvotes: 1

Related Questions