priore

Standardize AFNetworking calls

Apr 21st, 2016
705
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // [url]        : service url
  2. // [parameters] : optional parameters
  3. // [keyPath]    : optional root key to retrieve data
  4. // [class]      : object class that should return in the array
  5. //
  6. // eg. [PRHTTPSessionManager loadWithURL:@"http://mioservizio.com" parameters:nil keyPath:nil class:[ProductModel class] completion:....
  7. // eg. [PRHTTPSessionManager loadWithURL:@"http://mioservizio.com" parameters:nil keyPath:@"products.list" class:[ProductModel class] completion:....
  8. //
  9.  
  10. + (void)loadWithURL:(NSString*)url
  11.          parameters:(id)parameters
  12.             keyPath:(NSString*)keyPath
  13.               class:(Class)objClass
  14.          completion:(void(^)(NSArray *objects, NSError *error))completion
  15. {
  16.     AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
  17.     manager.responseSerializer = [AFJSONResponseSerializer serializer];
  18.     [manager GET:url parameters:parameters success:^(NSURLSessionDataTask *task, NSDictionary *responseObject)
  19.      {
  20.          NSArray *list;
  21.          if (keyPath == nil)
  22.              list = responseObject.allValues;
  23.          else if ([keyPath length] == 0)
  24.              list = @[responseObject];
  25.          else
  26.              list = [responseObject valueForKeyPath:keyPath];
  27.          NSMutableArray *objects = [NSMutableArray array];
  28.          [list enumerateObjectsUsingBlock:^(NSDictionary *dict, NSUInteger idx, BOOL * _Nonnull stop) {
  29.              if (dict.allKeys.count > 0) {
  30.                  if ([objClass instancesRespondToSelector:@selector(initWithJSONDictionary:)]) {
  31.                      __strong typeof(objClass) obj = [[objClass alloc] performSelector:@selector(initWithJSONDictionary:) withObject:dict];
  32.                      [objects addObject:obj];
  33.                  }
  34.              }
  35.          }];
  36.          
  37.          if (completion) {
  38.              completion(objects, nil);
  39.          }
  40.          
  41.      }
  42.          failure:^(NSURLSessionDataTask *task, NSError *error)
  43.      {
  44.          if (completion) {
  45.              completion(nil, error);
  46.          }
  47.      }];
  48. }
RAW Paste Data

Adblocker detected! Please consider disabling it...

We've detected AdBlock Plus or some other adblocking software preventing Pastebin.com from fully loading.

We don't have any obnoxious sound, or popup ads, we actively block these annoying types of ads!

Please add Pastebin.com to your ad blocker whitelist or disable your adblocking software.

×