Skip to content

Instantly share code, notes, and snippets.

@jyaunches
Last active December 10, 2015 22:39
Show Gist options
  • Save jyaunches/4504223 to your computer and use it in GitHub Desktop.
Save jyaunches/4504223 to your computer and use it in GitHub Desktop.
@interface SomeObjectFetcher ()
@property (nonatomic, strong) NSMutableData *responseData;
@end
@implementation SomeObjectFetcher
@synthesize networkActivityDelegate = _networkActivityDelegate;
+ (SomeObjectFetcher *) sharedInstance{
static AvailableFestivalFetcher *requestGenerator = nil;
if(!requestGenerator)
requestGenerator = [[AvailableFestivalFetcher alloc] init];
return requestGenerator;
}
- (void)startRequest{
self.responseData = [NSMutableData data];
[self startConnection:@""];
}
- (void)startConnection:(NSString *)additionalParams{
NSURL *remoteServerURL = [NSURL URLWithString:[NSString stringWithFormat:@"%@/festivals.json%@", remoteServerAddress, additionalParams]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:remoteServerURL
cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
timeoutInterval:15];
[request setHTTPMethod: @"GET"];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSError *myError = nil;
NSArray *res = [NSJSONSerialization JSONObjectWithData:self.responseData
options:NSJSONReadingMutableLeaves
error:&myError];
//check error
NSMutableArray *processedObjects = [[NSMutableArray alloc] init];
for(NSDictionary* result in res) {
[processedObjects addObject: [SomeDomainObject initWithInfo:[result objectForKey:@"itemKeyName"]]];
}
//notify delegate that network activity is finished
[self.networkActivityDelegate finishedActivity];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[self.responseData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[self.responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(@"Failed to retrieve items: %@", error);
[self.networkActivityDelegate somethingWentWrong];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment