首页 > 解决方案 > 您如何访问 Alamofire 5 didCompleteTaskNotification 通知中的响应数据?

问题描述

我刚刚完成了从 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
}

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

标签: swiftalamofire

解决方案


您可以DataRequest与通知相关联的信息中获取。

guard let request = notification.request as? DataRequest else { return }

// Do something with request.data

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


推荐阅读