Last active
December 18, 2015 10:39
-
-
Save Brayden/5769659 to your computer and use it in GitHub Desktop.
BB Standard iOS App API Wrapper. Direct questions to Brayden.
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
@interface APIWrapper : NSObject | |
@property (nonatomic, strong) NSArray *categories; | |
@property (nonatomic, assign) NSInteger loadingCount; | |
+ (void)apiEndpoint:(NSString *)endpoint completionBlock:(void (^)(NSDictionary *dictionary, NSError *error))completion; | |
+ (APIWrapper *)sharedManager; | |
@end | |
#import "APIWrapper.h" | |
@implementation APIWrapper | |
+ (void)apiEndpoint:(NSString *)endpoint completionBlock:(void (^)(NSDictionary *dictionary, NSError *error))completion { | |
NSOperationQueue *queue = [[NSOperationQueue alloc] init]; | |
queue.maxConcurrentOperationCount = NSOperationQueueDefaultMaxConcurrentOperationCount; | |
[queue setName:@"com.brandingbrand.api"]; | |
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@", BASE_URL, endpoint]]]; | |
[request setValue:@"XMLHttpRequest" forHTTPHeaderField:@"X-Requested-With"]; | |
[request setTimeoutInterval:15.0f]; | |
[[APIWrapper sharedManager] setLoadingCount:[[APIWrapper sharedManager] loadingCount] + 1]; | |
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *resposne, NSData *data, NSError *error) { | |
if(data != nil) { | |
NSError *jsonError; | |
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&jsonError]; | |
dispatch_async(dispatch_get_main_queue(), ^{ | |
completion(dictionary, nil); | |
}); | |
} else { | |
NSLog(@"API Error: %@", error.description); | |
} | |
[[APIWrapper sharedManager] setLoadingCount:[[APIWrapper sharedManager] loadingCount] - 1]; | |
}]; | |
} | |
#pragma mark - Singleton Setup - | |
+ (APIWrapper *)sharedManager { | |
static APIWrapper *sharedManager; | |
static dispatch_once_t token = 0; | |
dispatch_once(&token, ^{ | |
sharedManager = [[APIWrapper alloc] init]; | |
}); | |
return sharedManager; | |
} | |
- (id)init { | |
if (self = [super init]) { | |
self.categories = [[NSArray alloc] init]; | |
} | |
return self; | |
} | |
#pragma mark - Setter Methods - | |
- (void)setLoadingCount:(NSInteger)loadingCount { | |
_loadingCount = loadingCount; | |
if(loadingCount > 0) | |
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES; | |
else | |
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment