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

Alamofire 5 文件下载执行时间获取方法咨询(Swift 5)

获取Alamofire 5中请求/下载的总耗时

嘿,我刚完成Alamofire 4到5的升级,刚好碰到过和你一样的问题,给你梳理下两种场景下的解决方案:


1. 闭包回调方式(和Alamofire 4用法最接近)

Alamofire 5并没有完全移除Timeline相关的属性,在闭包回调的DataResponse或DownloadResponse里,依然可以直接访问timeline.totalDuration,用法和之前几乎一致:

请求任务示例

AF.request("https://example.com/api/data").responseData { response in
    // 获取从请求开始到响应序列化完成的总耗时
    let totalDuration = response.timeline.totalDuration
    print("请求总耗时:\(totalDuration)秒")
}

下载任务示例

AF.download("https://example.com/file.zip").responseData { response in
    let totalDuration = response.timeline.totalDuration
    print("下载总耗时:\(totalDuration)秒")
}

这里的timeline.totalDuration和你之前用的Alamofire 4版本的属性完全等价,都是返回从请求启动到响应处理完成的秒级时间间隔。


2. Async/Await 异步方式(Alamofire 5.5+支持)

如果你用了Alamofire 5新增的async/await语法,就需要通过URLSessionTask的metrics属性来获取总耗时:

do {
    // 发起异步请求并获取响应
    let (data, response) = try await AF.request("https://example.com/api/data").serializingData().response
    
    // 从任务的metrics中提取总耗时
    if let taskMetrics = response.task?.metrics {
        let totalDuration = taskMetrics.taskInterval.duration
        print("请求总耗时:\(totalDuration)秒")
    }
} catch {
    print("请求失败:\(error)")
}

这里的taskMetrics.taskInterval.duration对应了任务从创建到完成的完整时间周期,和timeline.totalDuration的统计范围一致。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 10:22:54