Skip to content

Instantly share code, notes, and snippets.

@HomerJSimpson
Last active August 29, 2015 14:10
Show Gist options
  • Save HomerJSimpson/0b51e7302a324cc7d6df to your computer and use it in GitHub Desktop.
Save HomerJSimpson/0b51e7302a324cc7d6df to your computer and use it in GitHub Desktop.
Waiting on a gcd task in a command line app
#import <Foundation/Foundation.h>
NSString *const retirementUrl = @"https://query.yahooapis.com/v1/public/yql/homerj/retirement?format=json";
int main(int argc, const char * argv[]) {
@autoreleasepool {
// insert code here...
NSURLSession *session = [NSURLSession sharedSession];
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
[[session dataTaskWithURL:[NSURL URLWithString:retirementUrl]
completionHandler:^(NSData *data,
NSURLResponse *response,
NSError *error) {
NSLog(@"in the callback");
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
if(!error) {
NSError *jsonError;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingAllowFragments
error:&jsonError];
if(!jsonError) {
NSString *body;
NSLog(@"response code:\t%ld", (long)httpResponse.statusCode);
NSLog(@"%@", body=(NSString*)[json valueForKeyPath:@"query.results.html.body"]);
NSMutableDictionary *results = [@{} mutableCopy];
[[body componentsSeparatedByString:@"&"]
enumerateObjectsUsingBlock:^(NSString *obj, NSUInteger idx, BOOL *stop) {
NSArray *components = [obj componentsSeparatedByString:@"="];
NSLog(@"component.count == %ld", components.count);
if(components.count > 1) {
results[components[0]] = [components[1] stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]
];
}
}];
NSLog(@"results = %@", results);
NSLog(@"filtering for powerball");
NSSet *powerball = [results keysOfEntriesPassingTest:^BOOL(id key, id obj, BOOL *stop) {
if([key hasPrefix:@"powerball"]) {
return YES;
}
return NO;
}];
NSLog(@"found %ld powerball entries", powerball.count);
NSSet *megamillions = [results keysOfEntriesPassingTest:^BOOL(id key, id obj, BOOL *stop) {
if([key hasPrefix:@"biggame"]) {
return YES;
}
return NO;
}];
NSLog(@"found %ld megamillions entries\n\n%@", megamillions.count, megamillions);
}
}
dispatch_semaphore_signal(semaphore);
}] resume];
NSLog(@"waiting");
long rc = dispatch_semaphore_wait(semaphore, dispatch_time(DISPATCH_TIME_NOW, 60.0 * NSEC_PER_SEC));
NSLog(@"rc == %ld", rc);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment