I load some data from from my webservice via a method using blocks and callbacks.
From my ViewController
I make a request to the data loading class and pass the callback block:
- (void)loadRadioStationList
{
[self.radioDataLoader getRadioStationList:^(NSArray *data, NSDictionary *dictData){
self.alphabetizedDictionary = [[NSDictionary alloc] initWithDictionary:dictData];
self.sectionIndexTitles = [[NSArray alloc] initWithArray:data];
[self.radioStationTableView reloadData];
}];
}
Then in the dataloading class the method is as so:
-(void) getRadioStationList:(void (^)(NSArray *data, NSDictionary *dictData))callback
{
NSString *string = RadioStationListURL;
NSURL *url = [NSURL URLWithString:string];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFXMLParserResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSXMLParser *XMLParser = (NSXMLParser *)responseObject;
[XMLParser setShouldProcessNamespaces:YES];
XMLParser.delegate = self;
[XMLParser parse];
callback((NSArray*)self.sectionIndexTitles, (NSDictionary*)self.alphabetizedDictionary);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error Retrieving Radio List"
message:[error localizedDescription]
delegate:nil
cancelButtonTitle:@"Ok"
otherButtonTitles:nil];
[alertView show];
}];
[operation start];
}
It loads the XML file and parses out the data and send the data back to my VC via the callback block.
I've a couple of questions:
- Is this an acceptable way of doing this? Would you prefer to see it done another (better) way?
- If I was to write an API, would passing the data from the API back to the calling class be a good way to work it, or is there a more suitable method for an API?