2

I'm using OneSignal to process notifications in my app. This is initiated in AppDelegate.swift where there is a function that handles received apps:

let notificationReceivedBlock: OSHandleNotificationReceivedBlock = { notification in
    print("Received Notification: \(notification!.payload.body)")
}

I then have a TabViewController with 5 tabs and each tab's navigationItem has a UINavigationBarButton that sends you to a messages view. I want to change the badge number in that button whenever a notification comes in to show that the user is getting new messages. I have a function inside every viewController (each of the 5 tabs) that will update this.

The problem is that the AppDelegate needs to call this function updateBadgeNumber and I don't know how to do this. Plus, some of the tabs may not even have been initialised yet. Does anyone know how to call functions in ViewControllers from the AppDelegate?

Thank you.

EDIT:

Found a solution thanks to @paulvs below. He linked me to an answer where I found this: Find Top View Controller in Swift

Community
  • 1
  • 1
Pelayo Martinez
  • 137
  • 1
  • 5
  • Don't call any method from there just post a notification and add an observer to your view controller – Leo Dabus Apr 21 '17 at 21:32
  • Thank you for the help! The problem with your suggestion was that OneSignal is initialised in the AppDelegate and you feed it its observer functions to initialise it, so I couldn't add observers to every class and then feed them in the AppDelegate – Pelayo Martinez Apr 22 '17 at 15:59

1 Answers1

1

The answer depends on whether your UITabBarController is the root view controller of your app.

  1. If your UITabBarController is the root view controller, you likely have a reference to it in your app delegate and can use UITabBarController's selectedViewController property to get the current view controller and then set the badge value. (If you don't have a reference, you can probably cast window.rootViewController to UITabBarController to access it.)
  2. If it's not, you can use code like this to find the currently visible view controller. (Then to access the UITabBarController, you can probably cast parentViewController to a UITabBarController, and from there access the other view controllers and set their badge values, too.)
Community
  • 1
  • 1
paulvs
  • 11,963
  • 3
  • 41
  • 66
  • 1
    Thank you so much! I used the Swift code from another answer in that link you gave me! So I basically get the top ViewController and then do a switch to find out which class it is and then cast it to that class and call its respective updateBadge() function. I'll add the code I used to this question – Pelayo Martinez Apr 22 '17 at 15:57