Last active
April 22, 2016 11:00
-
-
Save priore/b395f150d0c9c51b333d196cf15d6a89 to your computer and use it in GitHub Desktop.
Standardize AFNetworking calls
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // [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); | |
| } | |
| }]; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment