如何在静态方法内等待回调代码完成?

时间:2018-04-20 20:41:55

标签: swift swift4

我有这样的方法:

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)")
    }
}

我是从App Delegate调用的 -

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

方法内的打印输出正确的值。 App Delegate内的打印件为空白。我在概念上遗漏了一些东西。我知道回调比调用getScheduledForToday方法要晚,因此空白。问题是如何等待回调或是否有更好的方法来实现这一目标?

2 个答案:

答案 0 :(得分:0)

添加完成块

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

然后致电

Utility.getScheduledForToday { (result) in
   print("count: \(result)")
}

答案 1 :(得分:0)

来自游乐场:

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)")
}