Skip to content

Instantly share code, notes, and snippets.

@widescape
Last active August 29, 2015 13:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save widescape/10466762 to your computer and use it in GitHub Desktop.
Save widescape/10466762 to your computer and use it in GitHub Desktop.
Load JSON without bloated AFNetworking
#import <Foundation/Foundation.h>
@interface JSONFromConnection : NSObject
+ (void)sendAsynchronousRequest:(NSURLRequest*)request completeWith:(void (^)(id dataFromJSON, NSError *connectionOrJSONError))complete;
@end
#import "JSONFromConnection.h"
@implementation JSONFromConnection
+ (void)sendAsynchronousRequest:(NSURLRequest*)request completeWith:(void (^)(id dataFromJSON, NSError *connectionOrJSONError))complete {
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if (connectionError) {
complete(nil, connectionError);
}
else {
NSError *jsonError = nil;
NSMutableData *unserializedData = [NSJSONSerialization JSONObjectWithData: data options:NSJSONReadingMutableContainers error:&jsonError];
if (jsonError) {
complete(data, jsonError);
}
else {
complete(unserializedData, nil);
}
}
}];
}
@end
- (void)fetchData
{
NSString *urlAsString = [NSString stringWithFormat:@"https://api.example.com/%@/%@", apiKey, yourQuery];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlAsString] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20];
__weak UIViewController *weakSelf = self;
[JSONFromConnection sendAsynchronousRequest:request completeWith:^(id dataFromJSON, NSError *connectionOrJSONError) {
if (connectionOrJSONError) {
// Handle the error
weakSelf.…
}
else {
// Do something with dataFromJSON (NSMutableData)
weakSelf.…
}
[weakSelf broadcastWeatherDataFor:index onQueriedLocation:queriedLocation];
}];
}
#import "AppDelegate.h"
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application willFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Setup URL Caching (always a good idea)
NSURLCache *URLCache = [[NSURLCache alloc] initWithMemoryCapacity:4 * 1024 * 1024
diskCapacity:20 * 1024 * 1024
diskPath:nil];
[NSURLCache setSharedURLCache:URLCache];
return YES;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment