Search code examples
swiftalamofire

How do you access response data in Alamofire 5 didCompleteTaskNotification notification?


I just got done upgrading from Alamofire 4 to 5. Everything went fine except for logging responses for debugging. In Alamofire 4, you had access to the response data.

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)")
        }
    }
}

In Almaofire 5, you don't seem to have access to the response data. The only thing in the userInfo is Alamofire.Request accessed through notification.request.

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

Does anyone know how to access the response data?


Solution

  • You can get the Data from the Request associated with the notification.

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

    However, I'd suggest transitioning to our EventMonitor protocol for logging, as it gives you access to a lot more events. You can read more in our documentation.