get responseObject on failure block AFNetworking 3.0

后端 未结 6 1649
别那么骄傲
别那么骄傲 2020-12-09 03:02

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:param         


        
相关标签:
6条回答
  • 2020-12-09 03:23
    - (void)requestWithURL:(NSString *)url parameterDictionary:(NSMutableDictionary *)data  requestType:(NSString *)reqType  handler:(NSObject *)handler selector:(SEL)selector
    {
    
      // reqType is POST or GET
      // handler would be self if you define selector method in same class
      AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    
      NSMutableURLRequest *req = [[AFJSONRequestSerializer serializer] requestWithMethod:reqType URLString:[NSString stringWithFormat:@"%@",url] parameters:nil error:nil];
    
    req.timeoutInterval= [[[NSUserDefaults standardUserDefaults] valueForKey:@"timeoutInterval"] longValue];
    [req setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [req setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    if (data != nil) {
        NSLog(@"Data is not nil");
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:data options:0 error:&error];
        NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        [req setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
    
    }else{
        NSLog(@"Data is nil");
    }
    
    [[manager dataTaskWithRequest:req completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
    
        if (!error) {
    //            NSLog(@"Reply JSON: %@", responseObject);
            [handler performSelector:selector withObject:responseObject];
            if ([responseObject isKindOfClass:[NSDictionary class]]) {
                //blah blah
            }
        } else {
            NSLog(@"Error: %@, %@, %@", error, response, responseObject);
            [handler performSelector:selector withObject:responseObject];
        }
    }] resume];
    }
    
    0 讨论(0)
  • 2020-12-09 03:27

    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)
    
    0 讨论(0)
  • 2020-12-09 03:32
    let responseData:NSData = (error as NSError).userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] as! NSData
    let s :String = String(data: responseData as Data, encoding: String.Encoding.utf8)!
    

    For Swift 3

    0 讨论(0)
  • 2020-12-09 03:35

    I've found solution at 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
    

    And then assign it to your manager:

    self.manager.responseSerializer = [ResponseSerializer serializer];
    
    0 讨论(0)
  • 2020-12-09 03:36

    Fixed some code here, properly handling optionals. Swift 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)")
        }
    }
    
    0 讨论(0)
  • 2020-12-09 03:39

    I have found a solution for this which works perfectly. In swift

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

    and Objective-C code is

        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);
              }
          }
    }
    
    0 讨论(0)
提交回复
热议问题