получить responseObject при блокировке отказа AFNetworking 3.0

как я могу получить строку ответа из блока отказа в AFNetworking 3.x,

В версии 2.x это можно было сделать так:

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

но в версии 3.x нет операции в параметре возвращаемого блока, как показано ниже:

[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);
}];

поэтому я надеялся, что кто-то сможет этого добиться.


person Alexy Ibrahim    schedule 29.01.2016    source источник


Ответы (5)


Просто сделайте это в своем блоке отказа: -

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

Для Swift:-

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

Обновлено для Swift 4.1

var errResponse: String = String(data: (error._userInfo![AFNetworkingOperationFailingURLResponseDataErrorKey] as! Data), encoding: String.Encoding.utf8)!
print(errResponse)
person Vizllx    schedule 29.01.2016
comment
что делать в свисте? - person Max; 01.03.2016
comment
что, если я хочу загрузить изображение с URL-адреса ios - person ios developer; 30.08.2016
comment
@Vizllx отклонит AppStore, если я использую error._userInfo - person nickypatson; 24.02.2020

Я нашел решение для этого, которое отлично работает. В быстром

if let userInfo : NSDictionary = error.userInfo as NSDictionary {
     if let innerError : NSError = userInfo.objectForKey("NSUnderlyingError") as? NSError {

         if let innerUserInfo : NSDictionary = innerError.userInfo as NSDictionary {

              if innerUserInfo.objectForKey(AFNetworkingOperationFailingURLResponseDataErrorKey) != nil {
                   let StrError = NSString(data: innerUserInfo.objectForKey(AFNetworkingOperationFailingURLResponseDataErrorKey) as! NSData, encoding: NSUTF8StringEncoding)

                   print(StrError)
              }
         } else if let errResponse: String = String(data: (error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] as! NSData), encoding: NSUTF8StringEncoding) {
              print(errResponse)
         }
     }

}

и код Objective-C

    NSDictionary *userinfo1 = [[NSDictionary alloc] initWithDictionary:error.userInfo];

if(userinfo1) {
      NSError *innerError = [userinfo1 valueForKey:@"NSUnderlyingError"];
      if(innerError) {
         NSDictionary *innerUserInfo = [[NSDictionary alloc] initWithDictionary:innerError.userInfo];
         if(innerUserInfo)
         {
              if([innerUserInfo objectForKey:AFNetworkingOperationFailingURLResponseDataErrorKey])
              {
                   NSString *strError = [[NSString alloc] initWithData:[innerUserInfo objectForKey:AFNetworkingOperationFailingURLResponseDataErrorKey] encoding:NSUTF8StringEncoding];
                            NSLog(@"Error is : %@",strError);
              }
         }
      } else
      {
           NSString *errResponse = [[NSString alloc] initWithData:[userinfo1 valueForKey:@"AFNetworkingOperationFailingURLResponseDataErrorKey"] encoding:NSUTF8StringEncoding];

          if(errResponse)
          {
               NSLog(@"%@",errResponse);
          }
      }
}
person Max    schedule 01.03.2016

Я нашел решение на GitHub:

@interface ResponseSerializer : AFJSONResponseSerializer
@end

@implementation ResponseSerializer

- (id)responseObjectForResponse:(NSURLResponse *)response
                       data:(NSData *)data
                      error:(NSError *__autoreleasing *)errorPointer
{
    id responseObject = [super responseObjectForResponse:response data:data error:errorPointer];
    if (*errorPointer) {
        NSError *error = *errorPointer;
        NSMutableDictionary *userInfo = [error.userInfo mutableCopy];
        userInfo[@"responseObject"] = responseObject;
        *errorPointer = [NSError errorWithDomain:error.domain code:error.code userInfo:[userInfo copy]];
    }
    return responseObject;
}

@end

А затем назначьте его своему менеджеру:

self.manager.responseSerializer = [ResponseSerializer serializer];
person landonandrey    schedule 15.06.2016

let responseData:NSData = (error as NSError).userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] as! NSData
let s :String = String(data: responseData as Data, encoding: String.Encoding.utf8)!

Для Свифт 3

person user1969245    schedule 25.11.2016

Здесь исправлен некоторый код, правильно обрабатывающий опции. Свифт 3(.1)...

let nserror = error as NSError
if let errordata = nserror.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] as? Data {
    if let errorResponse = String(data: errordata, encoding: String.Encoding.utf8) {
        print("errorResponse: \(errorResponse)")
    }
}
person Jonny    schedule 13.11.2017