1

I have a method like this:

class Utility{
    static var todaysNotifications = [String]()
    static func getScheduledForToday() {
        _ = UNUserNotificationCenter.current().getPendingNotificationRequests { (notificationRequests) in
            for notificationRequest in notificationRequests {
                //some logic here
                todaysNotifications.append("some value based on logic")
            }
        }
        print("count: \(todaysNotifications.count)")
    }
}

I'm calling this from the App Delegate -

Utility.getScheduledForToday()
print("count: \(Utility.todaysReminders.count)")

The print inside the method prints proper value. The print inside the App Delegate is blank. I'm missing something conceptually. I know the callback is finishing later than the call to the getScheduledForToday method and hence the blank. The question is how to wait for the callback or are there better ways to achieve this?

BallpointBen
  • 9,406
  • 1
  • 32
  • 62
DS.
  • 2,846
  • 4
  • 30
  • 35

2 Answers2

0

Add a completion block

static func getScheduledForToday(completion: (_ result:Int) -> Void) {
   completion(sendedValue)
}

then call

Utility.getScheduledForToday { (result) in
   print("count: \(result)")
}
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87
0

From playground:

import UserNotifications

func getPendingNotificationRequests(completionHandler: @escaping ([String]) -> Void) {
    completionHandler(["Notif1", "Notif2"])
}

class Utility{
    static var todaysNotifications = [String]()
    static func getScheduledForToday(_ completionHandler: @escaping () -> Void) {
        getPendingNotificationRequests { notifications in
            notifications.forEach { todaysNotifications.append($0) }
            completionHandler()
        }
    }
}

Utility.getScheduledForToday {
    print("count: \(Utility.todaysNotifications.count)")
}
BallpointBen
  • 9,406
  • 1
  • 32
  • 62
Vlad Khambir
  • 4,313
  • 1
  • 17
  • 25