You probably have come across this situation before, you want to connect to Twitter and display the recent tweets of a given user in your app. Well, here’s how to get up and running.

twitter-posts-1

At the end of this tutorial, you will be able to download a sample Xcode project that loads a Twitter feed into a UICollectionView. This is just one of the features of the Newsfeeder template. The complete template does loads more. You can load the most recent posts of any WordPress blog or valid RSS Feed, display a Facebook feed and more. Check it out here.

Let’s get started with the tutorial.

Authenticating a User’s Account

To be able to access the needed information from Twitter, we need to use a logged in account. To do so, we are going to access the saved account into the Settings app of the phone, and use the AccountStore class included in iOS 6. so here’s the code to get it:

self.accountStore = [[ACAccountStore alloc] init];
ACAccountType *twitterAccountType = [self.accountStore
                                         accountTypeWithAccountTypeIdentifier:
                                         ACAccountTypeIdentifierTwitter];
 
    dispatch_async(dispatch_get_global_queue(
                                             DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [self.accountStore
         requestAccessToAccountsWithType:twitterAccountType
         options:nil completion:^(BOOL granted, NSError *error)
         {
             if (granted)
             {
                 NSArray *twitterAccounts = [self.accountStore
                                             accountsWithAccountType:twitterAccountType];
 
                 NSString *twitterAccountIdentifier = [[NSUserDefaults standardUserDefaults] objectForKey:AccountTwitterSelectedIdentifier];
 
                 self.account = [self.accountStore accountWithIdentifier:twitterAccountIdentifier];
 
                 if (self.account)
                 {
                     dispatch_async(dispatch_get_main_queue(), ^{
 
                         [[NSNotificationCenter defaultCenter] postNotificationName:AccountTwitterAccessGranted object:nil];
                     });
                 }
                 else
                 {
                     [[NSUserDefaults standardUserDefaults] removeObjectForKey:AccountTwitterSelectedIdentifier];
 
                     [[NSUserDefaults standardUserDefaults] synchronize];
 
 
                         self.account = [twitterAccounts lastObject];
 
                         dispatch_async(
                                        dispatch_get_main_queue(), ^{
 
                                            [[NSNotificationCenter defaultCenter] postNotificationName:AccountTwitterAccessGranted
                                             object:nil];
                                        });
 
                 }
             }
         }];
    });

This gives us access to the current account from the Settings app, that will be used for authentication in the following requests.

Getting the Twitter profile information

Now that we have the authentication covered, we are going to get the Profile information of the targeted account. Here’s how:

NSURL* url = [NSURL URLWithString:@"http://api.twitter.com/1.1/users/show.json"];
    NSDictionary* params = @"screen_name";
 
    SLRequest *request = [SLRequest requestForServiceType:SLServiceTypeTwitter
                                            requestMethod:SLRequestMethodGET
                                                      URL:url parameters:params];
 
    request.account = self.account;
 
    [request performRequestWithHandler:^(NSData *responseData,
                                         NSHTTPURLResponse *urlResponse, NSError *error) {
 
 
        if (error)
        {
            NSString* errorMessage = [NSString stringWithFormat:@"There was an error reading your Twitter feed. %@",
                                      [error localizedDescription]];
 
            [[AppDelegate instance] showError:errorMessage];
        }
        else
        {
            NSError *jsonError;
            NSDictionary *responseJSON = [NSJSONSerialization
                                     JSONObjectWithData:responseData
                                     options:NSJSONReadingMutableLeaves
                                     error:&jsonError];
 
	    dispatch_async(dispatch_get_main_queue(), ^{
                    self.profile = responseJSON;
                    [self setupProfile];
                });
 
 
        }
    }];

The code above connects to the Twitter API v1.1 using the url parameter. The response is a JSON object that is parsed using the NSJSONSerialization class in iOS.

Getting the Twitter feed

To accomplish this we will set a limit for how many items we want from the feed and pass the screen name we want to query. Using the returned array we’ll populate the collection view.

NSURL* url = [NSURL URLWithString:@"https://api.twitter.com/1.1/statuses/user_timeline.json"];
    NSDictionary* params = @{@"count" : @"50", @"screen_name" : @”twitterUsernameHere”};
 
    SLRequest *request = [SLRequest requestForServiceType:SLServiceTypeTwitter
                                            requestMethod:SLRequestMethodGET
                                                      URL:url parameters:params];
 
    request.account = self.account;
 
    [request performRequestWithHandler:^(NSData *responseData,
                                         NSHTTPURLResponse *urlResponse, NSError *error) {
 
        if (error)
        {
            NSString* errorMessage = [NSString stringWithFormat:@"There was an error reading your Twitter feed. %@",
                                      [error localizedDescription]];
 
            [[AppDelegate instance] showError:errorMessage];
        }
        else
        {
            NSError *jsonError;
            NSArray *responseJSON = [NSJSONSerialization
                                     JSONObjectWithData:responseData
                                     options:NSJSONReadingAllowFragments
                                     error:&jsonError];
           dispatch_async(dispatch_get_main_queue(), ^{
                    self.items = responseJSON;
                [self.collectionView reloadData];
                });
        }
    }];

The code above loads the Twitter stream of the user with the username “twitterUserNameHere”. The JSON response is again parsed and loaded into a UICollectionView that you see below.

Displaying the Twitter posts in a grid

Below you will see the final screen layout of the Twitter posts. We are using a bit of a special layout for the collection view. It resembles the Pinterest layout, something not defaultly accessible from the SDK. But using Nelson’s UICollectionViewWaterfallLayout we are able to display the feeds in a nicer way.

twitter-posts

Download the Final Sample Project

In a nutshell, that’s all folks. You probably will want to download the full sample here and browse the project to see how everything was implemented in full detail.

7 comments

  1. r.b.niranjan

    Thanks for post this usefull information. 🙂

    Could you please post about how to retweet a tweet . I really need it.

    Thanks

  2. Skip

    A great walkthrough, Tope, and I love the Newsfeeder template, makes building things super easy. Thanks again!

  3. RJD

    brilliant walkthrough, i’m quite new to this and wanted to just throw my sports scores twitter feed into an app as view only could you point me in the right direction

    thanks

  4. tor101

    when i compile the code in xcode5 and run it – only the blank template comes up – none of the information is populated. Can you pls advise how i can fix this?