I need to download data from a JSON, and assign the data to an NSData
outside the NSOperationQueue
. Here is my code:
-(void)parsingInfo {
NSURL *url = [NSURL URLWithString:@"http://someJSON.json"];
NSData *data;
[NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:url] queue:downloadQueue completionHandler:^(NSURLResponse* response, NSData* jsonData, NSError* error){
if(error)
{
// Error Downloading data
NSLog(@"Error");
}
else
{
data = jsonData;
}
}];
if (data) {
NSError *error;
NSDictionary *JSONDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
application = [JSONDic objectForKey:@"Applications"];
NSArray *featured = [JSONDic objectForKey:@"Featured"];
NSDictionary *dict2;
dict2 = [featured objectAtIndex:0];
} else {
NSLog(@"Error, no data!");
}
}
If you want to wait for 'data' to be filled before reaching to 'if (data)' statement then either.. a) Make synchronousRequest call.
+ (NSData *)sendSynchronousRequest:(NSURLRequest *)request returningResponse:(NSURLResponse **)response error:(NSError **)error
OR,
b) user semaphores to block/interrupt this thread until you receive data.
-(void)parsingInfo
{
NSURL *url = [NSURL URLWithString:@http://someJSON.json];
__block NSData *data;
// Create a semaphore to block this thread ( or run loop) until we get response back from server.
dispatch_semaphore_t waitSemaphore = dispatch_semaphore_create(0);
[NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:url] queue:downloadQueue completionHandler:^(NSURLResponse* response, NSData* jsonData, NSError* error){
if(error)
{
// Error Downloading data
NSLog(@"Error");
}
else
{
data = jsonData;
}
// Signal to release the semaphore (i.e. unblock the current thread).
dispatch_semaphore_signal(waitSemaphore);
}];
// A dispatch semaphore is an efficient implementation of a traditional counting semaphore. Dispatch semaphores call down
// to the kernel only when the calling thread needs to be blocked. If the calling semaphore does not need to block, no kernel call is made.
while (dispatch_semaphore_wait(waitSemaphore, DISPATCH_TIME_NOW))
{
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:10]];
}
// Release the semaphore.
dispatch_release(waitSemaphore);
if (data) {
NSError *error;
NSDictionary *JSONDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
application = [JSONDic objectForKey:@"Applications"];
NSArray *featured = [JSONDic objectForKey:@"Featured"];
NSDictionary *dict2;
dict2 = [featured objectAtIndex:0];
} else {
NSLog(@"Error, no data!");
}
}
Feel free to ask any questions.