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

Swift嵌套CompletionHandler异常:getNextSession未执行问题求助

Swift嵌套CompletionHandler调用失效问题排查与修复

你的代码存在几处关键错误,直接导致嵌套的getNextSession函数无法执行,以下是问题分析和修复方案:

问题根源

  1. 方法名拼写错误:submitSerice.subit() 存在两处拼写问题——submitSerice应为submitService,subit应为submit,这会导致submitService的提交请求根本没被正确触发,后续成功分支自然不会执行。
  2. 闭包参数名不匹配:在getNextSession的闭包中,你声明的参数是response,但switch判断时用了未定义的sessionResponse,这会引发编译错误,阻断后续逻辑。
  3. 服务实例拼写错误:nextSesssionService多了一个s,应为nextSessionService,若此处拼写错误,即使单独调用getNextSession正常,嵌套时也会因实例不存在导致逻辑中断。

修复后的完整代码

func submit(completionHandler: @escaping (Result<MyResult, Error>) -> Void) {
    submitService.submit() { [weak self] result in
        switch result {
        case .success(let submitResponse):
            self?.getNextSession() { response in
                switch response {
                case .success(let nextSession):
                    // 此处可处理nextSession相关逻辑
                    completionHandler(.success(submitResponse))
                case .failure(let error):
                    completionHandler(.failure(error))
                }
            }
        case .failure(let error):
            completionHandler(.failure(error))
        }
    }
}

func getNextSession(completionHandler: @escaping (Result<NextSession, Error>) -> Void) {
    print("Calling getNextSession()")
    nextSessionService.nextSession() { result in
        switch result {
        case .success(let response):
            completionHandler(.success(response))
        case .failure(let error):
            completionHandler(.failure(error))
        }
    }
}

额外注意点

  • 检查self生命周期:如果self在submitService.submit()回调触发前已被释放,self?.getNextSession()会静默不执行,可根据业务场景调整引用方式(比如在回调内先判断self是否存在)。
  • 线程调度:若API调用在后台线程执行,后续涉及UI更新的操作需切换回主线程。

内容的提问来源于stack exchange,提问作者Oliver Bajus

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 09:20:13