Skip to content

Instantly share code, notes, and snippets.

@rogerluan
Last active November 18, 2015 13:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rogerluan/67e12e12195648a801d6 to your computer and use it in GitHub Desktop.
Save rogerluan/67e12e12195648a801d6 to your computer and use it in GitHub Desktop.
Code snippet for blog series.
- (void)reloadData {
[self.refreshControl beginRefreshing];
//chamada em background
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//requisição dos dados do servidor
NSError *err = nil;
NSArray *json = nil;
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:kURL]];
//verifica a resposta do servidor
if (data == nil) {
err = [NSError errorWithDomain:NSStringFromClass([self class]) code:0
userInfo:@{NSLocalizedDescriptionKey: @"Nenhum dado retornou do servidor"}];
}
else { //se for válida, tenta deserializá-la em um json
json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&err][@"top"];
}
//manipula o resultado na main thread
dispatch_async(dispatch_get_main_queue(), ^{
//verifica se algo deu errado na requisição, ou na manipulação para transformar a resposta do servidor em um json
if (err) {
[self.refreshControl endRefreshing];
UIAlertController *alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"Oops...", nil) message:[NSString stringWithFormat:NSLocalizedString(@"Ocorreu Um Erro\n\n%@",nil),err.localizedDescription] preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel handler:nil];
[alert addAction:cancelAction];
[self presentViewController:alert animated:YES completion:nil];
}
else {
//converte os objetos do servidor no nosso modelo de objetos
NSMutableArray *items = [NSMutableArray array];
for (NSDictionary *jsonItem in json) {
TableData *item = [[TableData alloc] initWithJSON:jsonItem];
item.position = [NSNumber numberWithInteger:[json indexOfObject:jsonItem]+1];
[items addObject:item];
}
//salva os objetos e atualiza a table view
[self.refreshControl endRefreshing];
self.data = items;
[self.tableView reloadData];
}
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment