Skip to content

Instantly share code, notes, and snippets.

@soltrinox
Last active August 29, 2015 14:27
Show Gist options
  • Select an option

  • Save soltrinox/095d42f5f08205a2404c to your computer and use it in GitHub Desktop.

Select an option

Save soltrinox/095d42f5f08205a2404c to your computer and use it in GitHub Desktop.
BLOCK obj-c async call to JSON REST API GCD BLOCK
dispatch_queue_t myQueue = dispatch_queue_create("My Queue",NULL);
dispatch_async(myQueue, ^{
// Perform long running process
NSArray *new = [self parseJsonResponse:@"https://pixabay.com/api/?username=soltrinox0&key=e4a2af6f6d7e4869afa1&q=fashion+woman&image_type=photo&orientation=vertical&min_width=350&per_page=50"];
NSLog(@"%@", new );
NSMutableArray* offers = [NSMutableArray array];
for (int i = 0; i < [new count]; i++) {
NSDictionary *ip = [new objectAtIndex:i];
Offer *ot = [[Offer alloc] initWithDict:ip];
[offers addObject:ot];
}
dispatch_async(dispatch_get_main_queue(), ^{
// Update the UI
[[SimpplSingleton sharedManager] setNewArray:offers];
DraggableViewBackground *draggableBackground = [[DraggableViewBackground alloc]initWithFrame:self.view.frame ];
[self.view addSubview:draggableBackground];
});
});
- (NSArray *)parseJsonResponse:(NSString *)urlString
{
NSError *error;
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"GET"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse: nil error:&error];
if (!data)
{
NSLog(@"Download Error: %@", error.localizedDescription);
UIAlertView *alert =
[[UIAlertView alloc]initWithTitle:@"Error"
message:[NSString stringWithFormat:@"Error : %@",error.localizedDescription]
delegate:self
cancelButtonTitle:@"Ok"
otherButtonTitles:nil];
[alert show];
return nil;
}
// Parsing the JSON data received from web service into an NSDictionary object
NSDictionary *JSON =
[NSJSONSerialization JSONObjectWithData: data
options: NSJSONReadingMutableContainers
error: &error];
NSArray *ret = [NSArray arrayWithArray:[JSON objectForKey:@"hits"]];
NSLog(@"Response JSON=%@", ret );
return ret;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment