Skip to content
This repository has been archived by the owner on Oct 5, 2019. It is now read-only.

Showing Timelines

Eric Frohnhoefer edited this page Dec 8, 2017 · 3 revisions

Twitter Kit allows you to create Search, User, Collection, and List Timelines in your app. You just need to provide the appropriate values for each type of data source, and the Timeline will handle making the proper API requests, recycling UITableViewCell s, and loading new Tweets as the user scrolls.

The list of supported parameters for each timeline can be found in their respective designated headers. Note that the data source parameters are immutable once set.

For example, here is all the code required to implement a List Timeline in your app:

// Objective C

// ListTimelineViewController.h 
#import <UIKit/UIKit.h>
#import <TwitterKit/TwitterKit.h>

@interface ListTimelineViewController : TWTRTimelineViewController
@end

// ListTimelineViewController.m 
#import "FABListTimelineViewController.h" 
#import <TwitterKit/TwitterKit.h> 

@implementation ListTimelineViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    TWTRAPIClient *APIClient = [[TWTRAPIClient alloc] init];
    self.dataSource = [[TWTRListTimelineDataSource alloc] initWithListSlug:@"surfing" 
                                                       listOwnerScreenName:@"stevenhepting" 
                                                                 APIClient:APIClient];
}

@end

// Swift

// ListTimelineViewcontroller.swift
import UIKit
import TwitterKit

class ListTimelineViewController: TWTRTimelineViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        let client = TWTRAPIClient() self.dataSource = TWTRListTimelineDataSource(listSlug: "surfing", listOwnerScreenName: "stevenhepting", APIClient: client)
    }
}

Data Sources

User

A user data source is used to show a Timeline of Tweets for a certain user. All that is required is either the screenName or userID of the Twitter user to create the data source. You may also set includeRetweets or includeReplies to change the Tweets that show up in the Timeline.

let dataSource = TWTRUserTimelineDataSource(screenName: "twitterdev", APIClient: TWTRAPIClient()) dataSource.includeReplies = true

Search

Search timelines show search results with recent Tweets (~ 1 week) matching a given search query. Check the Search API for information about the advanced search query parameters that can be used in your search query string.

You can also edit the resultType, the geoCode, and the languageCode if you wish to narrow down search results to a particular subset of Tweets.

TWTRSearchTimelineDataSource(searchQuery: "#twitterflock", APIClient: TWTRAPIClient())

let dataSource = TWTRSearchTimelineDataSource(searchQuery: "puppies filter:media", APIClient: TWTRAPIClient())
dataSource.resultType = "popular"

List

A list on Twitter is a collection of users whose Tweets are combined into a single Timeline. This is often used to organize a source of content on a given topic such as US Senators or Bay Area Sports Players.

To create a list data source, you just require the username of the user who created the list, and the list slug or title.

TWTRListTimelineDataSource(listSlug: "surfing", listOwnerScreenName: "stevenhepting", APIClient: TWTRAPIClient())

Collection

A Twitter collection is a series of individual Tweets that have been manually curated. Often, these will be created through the TweetDeck app as described in this post.

The Twitter collections documentation describes collection timelines more fully and shows how they can be created and managed through the Twitter REST API.

After you've created a collection, you may view it on twitter.com, and copy the ID from the address bar. The example Twitter Music Superstars collection has ID 393773266801659904.

TWTRCollectionTimelineDataSource(collectionID: "393773266801659904", APIClient: TWTRAPIClient())

Showing Actions

To show action buttons you can set the showTweetActions boolean on the TWTRTimelineViewController.

class SearchTimelineViewController: TWTRTimelineViewController {
  convenience init() {
    let client = TWTRAPIClient()
    let dataSource = TWTRSearchTimelineDataSource(searchQuery: "#helloworld", APIClient: client)
    self.init(dataSource: dataSource)

    // Show Tweet actions
    self.showTweetActions = true
}

Filtering Tweets

Twitter Kit provides functionality to filter the Tweets displayed in your app, according to rules you provide. You can use this functionality to prevent showing Tweets with profane words, hide Tweets that link to blacklisted URLs, or block specific user's Tweets from appearing in your app. The rules can be managed in a standard JSON configuration file and used on any timeline in Twitter Kit for Android and iOS.

The TWTRTimelineDataSource supports the timelineFilter property to filter timeline contents. The TWTRTimelineFilter object supports filtering of Tweets by hashtags, URLs, handles, and keywords.

class SearchFilteredTimelineViewController: TWTRTimelineViewController {

  convenience init() {
      // define a search timeline
      let client = TWTRAPIClient()
      let dataSource = TWTRSearchTimelineDataSource(searchQuery: "twitter", apiClient: client)

      // filter the search timeline
      let filter = TWTRTimelineFilter()
      filter.keywords = [ "book", "phone" ]
      filter.hashtags = [ "#twitter", "#followme" ]
      filter.urls = [ "twitter.com" ]
      filter.handles = [ "ericfrohnhoefer", "benward", "vam_si", "katejaiheelee", "esacrosa" ]
      dataSource.timelineFilter = filter

      self.init(dataSource: dataSource)
  }
}

Using the TWTRTimelineFilter, you can specify four different filters with the available properties.

Filter Value Description
keywords Removes Tweets containing specified keywords in a Tweet’s text. Uses localized case-insensitive matching.
hashtags Removes Tweets containing specified hashtags. Uses localized case-insensitive matching.
handles Removes Tweets from specified users or replies to specified users. Uses case-insensitive matching.
urls Removes Tweets containing URLs from specified domain. Supports internationalized domain names.

You can easily load your filter settings using a JSON configuration file, like so:

{
  "keywords": [
    "dummy"
  ],
  "hashtags": [
    "cookies"
  ],
  "handles": [
    "benward",
    "vam_si",
    "ericfrohnhoefer",
    "katejaiheelee",
    "esacrosa"
  ],
  "urls": [
    "example.com"
  ]
}
class SearchFilteredTimelineViewController: TWTRTimelineViewController {
  convenience init() {
    let client = TWTRAPIClient()
    let dataSource = TWTRSearchTimelineDataSource(searchQuery: "twitter", apiClient: client)

    // filter the search timeline by loading the json file from bundle
    if let jsonData = NSData(contentsOfFile: Bundle.main.path(forResource: "filters", ofType: "json")!) {
      do {
          // parse dictionary values from the json file contents
          if let dictionary = try JSONSerialization.jsonObject(with: jsonData as Data, options: .allowFragments) as? [String : Any] {
              // simply supply a dictionary of values to the filters initializer
              if let filter = TWTRTimelineFilter(jsonDictionary: dictionary) {
                  dataSource.timelineFilter = filter
              }
          }
      } catch {
          // Could not load JSON file
      }
    }

    self.init(dataSource: dataSource)
  }
}

The above example loads the configuration from a JSON file in the bundle. However, you can store the configuration file locally or pull it from a remote server to deliver over-the-air updates to your filter configuration. You can use the same configuration file for Twitter Kit on both Android and iOS.