Skip to content

Instantly share code, notes, and snippets.

@mxswd
Created March 2, 2013 05:56
Show Gist options
  • Save mxswd/5069873 to your computer and use it in GitHub Desktop.
Save mxswd/5069873 to your computer and use it in GitHub Desktop.
//
// AFHTTPClient+MTLModel.h
// MXProjects
//
// Created by Maxwell Swadling on 2/03/13.
// Copyright (c) 2013 Maxwell Swadling. All rights reserved.
//
#import <AFNetworking/AFNetworking.h>
#import <Mantle.h>
@interface AFHTTPClient (MTLModel)
- (AFHTTPRequestOperation *)getObjects:(NSString *)path
forClass:(Class<MTLJSONSerializing>)klass
onKeypath:(NSString *)keypath
withParams:(NSDictionary *)params
success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSArray *objects, id JSON))success
failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON))failure;
@end
//
// AFHTTPClient+MTLModel.m
// MXProjects
//
// Created by Maxwell Swadling on 2/03/13.
// Copyright (c) 2013 Maxwell Swadling. All rights reserved.
//
#import "AFHTTPClient+MTLModel.h"
@implementation AFHTTPClient (MTLModel)
- (AFHTTPRequestOperation *)getObjects:(NSString *)path
forClass:(Class<MTLJSONSerializing>)klass
onKeypath:(NSString *)keypath
withParams:(NSDictionary *)params
success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSArray *objects, id JSON))success
failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON))failure {
NSURLRequest *request = [self requestWithMethod:@"GET" path:path parameters:params];
AFHTTPRequestOperation *op = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
id objJSON = [JSON copy];
NSMutableArray *buff = [[NSMutableArray alloc] initWithCapacity:0];
NSMutableArray *objects = [[NSMutableArray alloc] initWithCapacity:0];
NSArray *keyPathComponents = [keypath componentsSeparatedByString:@"."];
for (NSString *path in keyPathComponents) {
if ([objJSON isKindOfClass:[NSArray class]]) {
// Array, apply future keypaths to objects via map
[buff removeAllObjects];
[objJSON enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
[buff addObject:obj[path]];
}];
objJSON = buff;
} else if ([objJSON isKindOfClass:[NSDictionary class]]) {
// Dict, take value and repeat
objJSON = objJSON[path];
} else {
// TODO: Error
}
}
[objJSON enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
[objects addObject:[MTLJSONAdapter modelOfClass:klass fromJSONDictionary:obj]];
}];
success(request, response, [NSArray arrayWithArray: objects], JSON);
} failure:failure];
return op;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment