iosobjective-cafnetworkingafnetworking-3

get responseObject on failure block AFNetworking 3.0


how can I get the response string from failure block in AFNetworking 3.x,

In the 2.x version the way to do it was:

[manager GET:path parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSDictionary *dictionary_FetchResult = responseObject;
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSDictionary *dictionary_FetchResult = operation.responseObject;
}];

but in the 3.x version there is no operation in the returning block's parameter as shown below:

[manager POST:path parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
    NSDictionary *dictionary_FetchResult = responseObject;
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
    NSLog(@"Error: %@", error);
}];

so I was hoping if someone was able to achieve that.


Solution

  • Just do this in your failure block:-

     NSString* errResponse = [[NSString alloc] initWithData:(NSData *)error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] encoding:NSUTF8StringEncoding];
    NSLog(@"%@",errResponse);
    

    For Swift:-

    var errResponse: String = String(data: (error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] as! NSData), encoding: NSUTF8StringEncoding)
    NSLog("%@", errResponse)
    

    Updated for Swift 4.1

    var errResponse: String = String(data: (error._userInfo![AFNetworkingOperationFailingURLResponseDataErrorKey] as! Data), encoding: String.Encoding.utf8)!
    print(errResponse)