get responseObject on failure block AFNetworking 3.0

后端 未结 6 1781
别那么骄傲
别那么骄傲 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];
    }
    

提交回复
热议问题