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

自定义Alamofire 4.7 SessionManager请求立即被取消问题求助

解决Alamofire自定义SessionManager导致请求被取消(-999错误)的问题

这个问题我之前也踩过坑!你遇到的-999 cancelled错误,核心原因其实是自定义的sessionManager是局部变量,被ARC提前回收了。

当你在代码里创建局部的sessionManager并发起请求后,当前代码块执行完毕,这个sessionManager就会被系统的自动引用计数(ARC)销毁,对应的URLSession也会被释放,导致正在进行的请求直接被取消,就出现了-999的错误。而Alamofire的默认管理器是全局单例,一直保持着强引用,所以不会出现这个问题。

解决方案:给自定义SessionManager保持强引用

你只需要把sessionManager从局部变量改成全局变量,或者作为类的属性来持有它,确保它在请求完成前不会被释放。

方案1:全局声明SessionManager

// 把sessionManager放在全局作用域,保持强引用
let configuration = URLSessionConfiguration.default
configuration.timeoutIntervalForRequest = 20
let sessionManager = Alamofire.SessionManager(configuration: configuration)

// 在需要发起请求的地方直接使用
func sendMyRequest() {
    sessionManager.request("my url", method: .post, parameters: params, encoding: JSONEncoding.default, headers: header)
        .responseJSON(completionHandler: { (response) in
            if response.result.isSuccess{
                // 你的成功处理逻辑
            } else{
                // 你的错误处理逻辑
            }
        })
}

方案2:作为类的属性持有(推荐,更符合模块化)

如果是在网络管理类里使用,把sessionManager定义为类的成员变量:

class APIManager {
    // 类属性,保持强引用
    private let sessionManager: Alamofire.SessionManager
    
    init() {
        let configuration = URLSessionConfiguration.default
        configuration.timeoutIntervalForRequest = 20
        self.sessionManager = Alamofire.SessionManager(configuration: configuration)
    }
    
    func sendPostRequest(params: [String: Any], header: HTTPHeaders?) {
        sessionManager.request("my url", method: .post, parameters: params, encoding: JSONEncoding.default, headers: header)
            .responseJSON(completionHandler: { (response) in
                if response.result.isSuccess{
                    // 你的成功处理逻辑
                } else{
                    // 你的错误处理逻辑
                }
            })
    }
}

这样修改后,sessionManager会一直被持有,请求就能正常执行完成,不会再出现被取消的情况。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 06:54:47