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

标签 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)")

方法中的 print 打印正确的值。 App Delegate 里面的打印是空白的。我在概念上遗漏了一些东西。我知道回调比调用 getScheduledForToday 方法晚完成,因此空白。问题是如何等待回调,或者有更好的方法来实现吗?

最佳答案

添加一个完成 block

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

然后调用

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

关于swift - 如何在静态方法中等待回调代码完成?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49949439/

相关文章:

ios - 在 Swift 4 的 ContainerView 中查看

ios - 无法分配给属性 : 'item' is a 'let' constant (Swift 4)

swift - 如何将数据从 View Controller 传递到弹出 View Controller (swift/ios)

将多个 ViewController 推送到 NavigationController 堆栈时的 iOS 委托(delegate)问题

ios - swift3 日期到数据,数据到日期转换

ios - +[CATransaction synchronize] 搜索时在事务内调用

ios - 在 iOS 中以波形切割 View

swift - 如何从表格 View 单元格传递数据

swift - 展开 Segue 导航栏按钮 Xcode 8.0 Swift 3.0

swift - ARKIT - 如何粘贴两个物体