Objective-C Tips & Trick - Prioregroup.com
[Objective-C] Standardize AFNetworking calls
       
back

// [url]        : service url
// [parameters] : optional parameters
// [keyPath]    : optional root key to retrieve data 
// [class]      : object class that should return in the array
//
// eg. [PRHTTPSessionManager loadWithURL:@"http://mioservizio.com" parameters:nil keyPath:nil class:[ProductModel class] completion:....
// eg. [PRHTTPSessionManager loadWithURL:@"http://mioservizio.com" parameters:nil keyPath:@"products.list" class:[ProductModel class] completion:....
//

+ (void)loadWithURL:(NSString*)url
         parameters:(id)parameters
            keyPath:(NSString*)keyPath
              class:(Class)objClass
         completion:(void(^)(NSArray *objects, NSError *error))completion
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    [manager GET:url parameters:parameters success:^(NSURLSessionDataTask *task, NSDictionary *responseObject)
     {
         NSArray *list;
         if (keyPath == nil)
             list = responseObject.allValues;
         else if ([keyPath length] == 0)
             list = @[responseObject];
         else
             list = [responseObject valueForKeyPath:keyPath];
         NSMutableArray *objects = [NSMutableArray array];
         [list enumerateObjectsUsingBlock:^(NSDictionary *dict, NSUInteger idx, BOOL * _Nonnull stop) {
             if (dict.allKeys.count > 0) {
                 if ([objClass instancesRespondToSelector:@selector(initWithJSONDictionary:)]) {
                     __strong typeof(objClass) obj = [[objClass alloc] performSelector:@selector(initWithJSONDictionary:) withObject:dict];
                     [objects addObject:obj];
                 }
             }
         }];
         
         if (completion) {
             completion(objects, nil);
         }
         
     }
         failure:^(NSURLSessionDataTask *task, NSError *error)
     {
         if (completion) {
             completion(nil, error);
         }
     }];
}






Copyright © 1996-2018 Centro Studi Informatica di Danilo Priore. All rights reserved. P.I.10149810581.
prioregroup.com