You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在静态方法中等待异步回调代码执行完成?

解决异步回调等待问题的两种方案

这是个很常见的异步代码时序问题——你原来的getScheduledForToday里,UNUserNotificationCenter.getPendingNotificationRequests是异步执行的,闭包里的逻辑会在后台队列跑完,但外面的print根本不等它,直接就执行了,所以拿到的是空数组。

下面给你两种实用的解决办法,适配不同iOS版本:

方法1:用闭包回调(兼容iOS 14及以下)

把你的静态方法改成接受一个闭包参数,当异步回调完成、todaysNotifications填充好之后,再调用这个闭包通知外部代码执行后续逻辑。

修改后的Utility类:

class Utility{
    static var todaysNotifications = [String]()
    static func getScheduledForToday(completion: @escaping () -> Void) {
        // 先清空旧数据,避免重复添加
        todaysNotifications.removeAll()
        UNUserNotificationCenter.current().getPendingNotificationRequests { (notificationRequests) in
            for notificationRequest in notificationRequests {
                // 这里放你的原有逻辑
                let value = "some value based on logic" // 替换成你的实际计算值
                self.todaysNotifications.append(value)
            }
            // 异步逻辑完成,调用闭包通知外部
            completion()
        }
    }
}

然后在AppDelegate里这样调用:

Utility.getScheduledForToday {
    // 这里的代码会等异步回调完成后才执行
    print("count: \(Utility.todaysNotifications.count)")
    // 其他需要在数据准备好后执行的逻辑也放在这里
}

方法2:用Async/Await(iOS 15+ 推荐)

从iOS 15开始,UNUserNotificationCenter提供了异步版本的getPendingNotificationRequests()方法,配合Swift的async/await语法,可以让代码看起来像同步执行一样,更简洁易读。

修改后的Utility类:

class Utility{
    static var todaysNotifications = [String]()
    static func getScheduledForToday() async {
        // 清空旧数据
        todaysNotifications.removeAll()
        // 用await等待异步方法返回结果
        let notificationRequests = await UNUserNotificationCenter.current().pendingNotificationRequests()
        for notificationRequest in notificationRequests {
            // 你的原有逻辑
            let value = "some value based on logic"
            todaysNotifications.append(value)
        }
    }
}

在AppDelegate里调用时,需要把调用的方法标记为async(比如在application(_:didFinishLaunchingWithOptions:)里,要改成async func):

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) async -> Bool {
    await Utility.getScheduledForToday()
    print("count: \(Utility.todaysNotifications.count)")
    // 其他初始化逻辑
    return true
}

小提醒

不管用哪种方法,记得每次调用前清空todaysNotifications,不然多次调用会导致数组里的内容重复累积哦~

内容的提问来源于stack exchange,提问作者DS.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:31:38