Updating badge in a timed notification in swift 3?

455 Views Asked by At

I have been trying out Notification coding just to be able to add some to my app, however the big issue is, I can say ,

something.badge = 3

and such, but I can't say

something.badge +=1

or

something.badge = badge +1

so far, my code is like this

@IBAction func sendNotification(_ sender: Any) {// in this button you make a notification

      UIApplication.shared.applicationIconBadgeNumber = 1
    let asnwer1 = UNNotificationAction(identifier: "asnwer1",  title: "You are",  options: UNNotificationActionOptions.foreground)
    let asnwer2 = UNNotificationAction(identifier: "asnwer2", title: "Obviously you fucking are!" , options: UNNotificationActionOptions.foreground)
    let category = UNNotificationCategory(identifier: "myCategory", actions: [asnwer1, asnwer2], intentIdentifiers: [], options: [])
    UNUserNotificationCenter.current().setNotificationCategories([category])
   // created nitification

    let content = UNMutableNotificationContent()
    content.title = "Are you pathetic for not working out??"
    content.subtitle = "are you?? "
    content.body = "Are you sure?"
    content.categoryIdentifier = "myCategory"
    /////// THIS NEEDS IMPROVEMENT
    if  UIApplication.shared.applicationIconBadgeNumber == 1{
            content.badge = 2
    }
    if  UIApplication.shared.applicationIconBadgeNumber == 2{
        content.badge = 3
    }
    if  UIApplication.shared.applicationIconBadgeNumber == 3{
        content.badge = 4
    }
    if  UIApplication.shared.applicationIconBadgeNumber == 4{
        content.badge = 5
    }
    if  UIApplication.shared.applicationIconBadgeNumber == 5{
        content.badge = 6
    }
    if  UIApplication.shared.applicationIconBadgeNumber == 6{
        content.badge = 7
    }
    if  UIApplication.shared.applicationIconBadgeNumber == 7{
        content.badge = 8
    }
    if  UIApplication.shared.applicationIconBadgeNumber >= 8{
        content.badge = 9
    }


    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 10, repeats: false)
    let request = UNNotificationRequest(identifier: "timerDone", content: content, trigger: trigger)

    UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)// the previous lne created a let named request...youre using it here
}

The problem here is, I keep on saying, if the badge number is THAT specific number, make it That other specific number....is there any other way around it?

1

There are 1 best solutions below

0
On

I assume you want to simplify how to write all those conditions.

How about:

content.badge = Swift.min(9, UIApplication.shared.applicationIconBadgeNumber + 1)

Then no if clause needs to be written.