【问题标题】:How do you access response data in Alamofire 5 didCompleteTaskNotification notification?您如何访问 Alamofire 5 didCompleteTaskNotification 通知中的响应数据?
【发布时间】:2026-01-22 13:50:02
【问题描述】:

我刚刚完成了从 Alamofire 4 到 5 的升级。除了记录调试响应之外,一切都很好。在 Alamofire 4 中,您可以访问响应数据。

NotificationCenter.default.addObserver(forName: NSNotification.Name.Task.DidComplete, object: nil, queue: OperationQueue.main) { notification in
    if let responseData = notification.userInfo?[Notification.Key.ResponseData] as? Data {
        if responseData.count > 0 {
            let body = String(decoding: responseData, as: UTF8.self)
            print("Response Body: \(body)")
        }
    }
}

在 Almaofire 5 中,您似乎无权访问响应数据。 userInfo 中唯一的内容是通过 notification.request 访问的 Alamofire.Request。

NotificationCenter.default.addObserver(forName: Request.didCompleteTaskNotification, object: nil, queue: OperationQueue.main) { notification in
    // no response data here
}

有人知道如何访问响应数据吗?

【问题讨论】:

    标签: swift alamofire


    【解决方案1】:

    您可以从与通知关联的Request 中获取Data

    guard let request = notification.request as? DataRequest else { return }
    
    // Do something with request.data
    

    但是,我建议转换到我们的 EventMonitor 协议进行日志记录,因为它可以让您访问更多事件。你可以在our documentation阅读更多内容。

    【讨论】: