Skip to content

Instantly share code, notes, and snippets.

@gonzalezreal
Created November 1, 2012 17:49
Show Gist options
  • Select an option

  • Save gonzalezreal/3995339 to your computer and use it in GitHub Desktop.

Select an option

Save gonzalezreal/3995339 to your computer and use it in GitHub Desktop.
#import "TGRTimelineViewController.h"
#import "TGRTimeline.h"
#import "TGRTweet.h"
#import "TGRTwitterUser.h"
#import "ACAccountStore+Twitter.h"
static NSString * const kTweetCellIdentifier = @"TweetCell";
@interface TGRTimelineViewController ()
// Nuestra timeline
@property (strong, nonatomic) TGRTimeline *timeline;
// Indica si hay alguna petición en curso
@property (nonatomic, getter = isLoading) BOOL loading;
@end
@implementation TGRTimelineViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.title = NSLocalizedString(@"Timeline", @"");
// Configuramos nuestro refresh control para que llame
// a loadNewTweets
self.refreshControl = [[UIRefreshControl alloc] init];
[self.refreshControl addTarget:self
action:@selector(loadNewTweets)
forControlEvents:UIControlEventValueChanged];
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
// Si nuestra timeline no está creada, pedimos
// acceso a la cuenta de Twitter
if (!self.timeline) {
[self requestTwitterAccess];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// De momento vamos a utilizar una UITableViewCell
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kTweetCellIdentifier];
// Obtenemos el tweet correspondiente a la fila
TGRTweet *tweet = [self.fetchedResultsController objectAtIndexPath:indexPath];
// Configuramos la celda para que muestre el nombre de usuario y el texto del tweet
cell.textLabel.text = tweet.user.screenName;
cell.detailTextLabel.text = tweet.text;
return cell;
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
// Calculamos la distancia que queda para llegar al final de la tabla
CGFloat distanceToBottom = scrollView.contentSize.height - (scrollView.contentOffset.y + scrollView.frame.size.height);
// Antes de llegar al final cambiamos nuestro estado a 'loading', mostrando un indicador
// de actividad en el footer de la tabla
self.loading = (distanceToBottom <= 44);
// Si ya hemos llegado al final hacemos la petición para pedir tweets más antiguos
if (distanceToBottom == 0) {
[self loadOldTweets];
}
}
#pragma mark - Private methods
// Sobreescribimos el setter de la propiedad 'loading'
- (void)setLoading:(BOOL)loading
{
if (_loading != loading) {
_loading = loading;
if (_loading) {
// Creamos un indicador de actividad y lo configuramos como footer de
// la tabla
UIActivityIndicatorView *indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
indicator.contentMode = UIViewContentModeCenter;
CGRect frame = indicator.frame;
frame.size.height = 44.0;
indicator.frame = frame;
[indicator startAnimating];
self.tableView.tableFooterView = indicator;
}
else {
// Eliminamos el footer de la tabla
self.tableView.tableFooterView = nil;
}
}
}
- (void)requestTwitterAccess
{
// Obtenemos una referencia a nuestro account store
ACAccountStore *accountStore = [ACAccountStore tgr_sharedAccountStore];
// Definimos el bloque que vamos a ejecutar cuando nos permitan el acceso
// a las cuentas de twitter
void (^useTwitterAccount)(void) = ^{
// Obtenemos las cuentas de Twitter
NSArray *accounts = [accountStore tgr_twitterAccounts];
if ([accounts count]) {
// Creamos y configuramos la timeline con la primera de las cuentas
[self setupTimelineWithAccount:accounts[0]];
}
else {
NSLog(@"There are no Twitter accounts!!");
}
};
if ([accountStore tgr_twitterAccountAccessGranted]) {
// Si ya nos habían permitido el acceso, simplemente invocamos el bloque
useTwitterAccount();
}
else {
// Pedimos permiso para acceder a las cuentas de Twitter
[accountStore tgr_requestAccessToTwitterAccountsWithCompletionHandler:^(BOOL granted, NSError *error) {
if (granted) {
// Si nos lo conceden, invocamos el bloque en el hilo principal
dispatch_async(dispatch_get_main_queue(), useTwitterAccount);
}
}];
}
}
- (void)setupTimelineWithAccount:(ACAccount *)account
{
// Creamos la timeline con la cuenta de Twitter que nos han pasado
self.timeline = [[TGRTimeline alloc] initWithAccount:account];
// Creamos el fetchedResultsController pasándole la consulta para obtener todos
// los tweets y el managedObjectContext de la timeline
self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:[TGRTweet fetchRequestForAllTweets]
managedObjectContext:self.timeline.managedObjectContext
sectionNameKeyPath:nil
cacheName:nil];
// Pedimos los tweets más recientes
[self loadNewTweets];
}
- (void)loadNewTweets
{
// Le indicamos al refreshControl que vamos a refrescar el contenido
UIRefreshControl *refreshControl = self.refreshControl;
[refreshControl beginRefreshing];
// Pedimos los tweets más recientes a nuestra timeline
[self.timeline loadNewTweetsWithCompletionHandler:^(NSError *error) {
if (error) {
NSLog(@"Error loading new tweets: %@", [error localizedDescription]);
}
// Le indicamos al refreshControl que ya hemos refrescado el contenido
[refreshControl endRefreshing];
}];
}
- (void)loadOldTweets
{
// Pedimos tweets más antiguos a nuestra timeline
[self.timeline loadOldTweetsWithCompletionHandler:^(NSError *error) {
if (error) {
NSLog(@"Error loading old tweets: %@", [error localizedDescription]);
}
self.loading = NO;
}];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment