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

Show Tweets

Rajul Arora edited this page Jul 12, 2018 · 5 revisions

Twitter Kit provides the necessary authentication, REST API access, and TWTRTweetView to show both individual and timeline Tweets in your app.

Features

When showing Tweets you can configure:

  • The style (dark or light)
  • Colors (text, links, background)
  • Action Buttons
  • The delegate (TWTRTweetViewDelegate) to be notified of user interaction with the Tweet

NOTE: Tweets can be rendered using user authentication or guest authentication.

Display a Single Tweet

To show a single Tweet, you first need to load that Tweet from the network (see access-rest-api) and then create and configure a view with that Tweet model object. Then it may be added to the view hierarchy.

If you have stored Twitter API responses you can also construct Tweet model objects from static JSON (see Use Static JSON for Tweets).

  1. Import the Twitter kit framework
// Objective-C
#import <TwitterKit/TwitterKit.h>
// Swift
import TwitterKit
  1. Load Tweets from the network, then create TWTRTweetView in completion block

NOTE: If you are using a version prior to version 1.10.0 you will need to login as a guest before making the following requests.

// Objective-C
// Loading public Tweets do not require user auth
TWTRAPIClient *client = [[TWTRAPIClient alloc] init];
[client loadTweetWithID:@"20" completion:^(TWTRTweet *tweet, NSError *error) {
  if (tweet) {
    [weakSelf.tweetView configureWithTweet:tweet]
  } else {
    NSLog(@"Failed to load tweet: %@", [error localizedDescription]);
  }
}];
// Swift

var tweetView = TWTRTweetView?
let client = TWTRAPIClient()
client.loadTweet(withID: "20") { [weak self] (tweet, error) in
  if let t = tweet 
    if let tweetView = self?.tweetView {
      tweetView.configure(with: t)
    } else {
      self?.tweetView = TWTRTweetView(tweet: t, style: TWTRTweetViewStyle.regular) 
    }
  } else {
      print("Failed to load Tweet: \(error.localizedDescription)")
  }
}

Tweet View Style

There are two different styles for Tweet views: TWTRTweetViewStyleRegular and TWTRTweetViewStyleCompact. Regular Tweet views show their image above all other content, whereas compact Tweet views are designed to be put inside tableviews through the TWTRTweetTableViewCell and show their media below the Tweet text. Both allow the use of actions through the showActionButtons boolean.

Show Action Buttons

Tweet views have the option on whether to include action buttons for favorite and share. By default, they are hidden but may be shown by setting the showActionButtons property. For the favorite action, this will cause a standard login flow to begin to get the proper user to use to favorite this Tweet. If your app already has Twitter authentication tokens outside of Twitter Kit, you may want to see Using Existing Tokens <using-existing-tokens> to keep users from seeing a second authentication flow.

let tweetView = TWTRTweetView(tweet: newlyLoadedTweet)
tweetView.showActionButtons = true
self.addSubview(tweetView)

TWTRTweetView Demo

Configure Tweet View Colors & Themes

To change the colors of a Tweet view you have two options:

  1. Set the theme property of the TWTRTweetView.
// Objective-C
// Set the theme directly
tweetView.theme = TWTRTweetViewThemeDark;

// Use custom colors
tweetView.primaryTextColor = [UIColor yellowColor];
tweetView.backgroundColor = [UIColor blueColor];
// Swift
// Set the theme directly
tweetView.theme = .dark

// Use custom colors
tweetView.primaryTextColor = UIColor.yellow
tweetView.backgroundColor = UIColor.blue
  1. Set visual properties using the UIAppearanceProxy for TWTRTweetView.
// Objective-C
// Set all future tweet views to use dark theme using UIAppearanceProxy
[TWTRTweetView appearance].theme = TWTRTweetViewThemeDark;

// Use custom colors
[TWTRTweetView appearance].primaryTextColor = [UIColor yellowColor];
[TWTRTweetView appearance].backgroundColor = [UIColor blueColor];
[TWTRTweetView appearance].linkTextColor = [UIColor redColor];
// Swift
// Set all future tweet views to use dark theme using UIAppearanceProxy
TWTRTweetView.appearance().theme = .dark

// Use custom colors
TWTRTweetView.appearance().primaryTextColor = UIColor.yellow
TWTRTweetView.appearance().backgroundColor = UIColor.blue
TWTRTweetView.appearance().linkTextColor = UIColor.red

Play or Pause Inline Video

NOTE: To use inline videos in UICollectionView, you must to implement collectionView:didEndDisplayingCell:forItemAtIndexPath: and add pausing functionality. We check if a playable video exists on the tweet and plays if the media exists. So calling playVideo() on a tweet without media won't throw exception.

// Objective-C
// Pause the video
[tweetView pauseVideo];
// Start playing the video
[tweetView playVideo];
let tweetView = TWTRTweetView(tweet: newlyLoadedTweet)
// Pause the video
tweetView.pauseVideo()
// Start playing the video
tweetView.playVideo()

NOTE: If you wish for your videos to play muted when calling playVideo(), set the shouldPlayVideoMuted property to YES. If the user taps the play button on the video or if the user taps the fullscreen button, it will always play with sound.

Delegate Methods

You may respond to user actions on Tweet view to perform various actions. For example, you may want to show a webview with the Tweet details when a user taps the Tweet view.

To respond to delegate methods, implement the TWTRTweetViewDelegate protocol:

// Objective-C
// MyViewController.h
#import <TwitterKit/TwitterKit.h>

@interface MyViewController : UIViewController <TWTRTweetViewDelegate>
@end

// MyViewController.m
@implementation MyViewController : UIViewController <TWTRTweetViewDelegate>
// My stuff
@end

If you are using the TWTRTimelineViewController you may use the tweetViewDelegate property on the controller to have the timeline controller to pass along the delegate to the Tweet views that it shows.

You may also register to receive notifications regarding various actions that occur on the Tweet views. This can be useful for recording metrics information for analytics purposes while still keeping the default functionality that Twitter Kit provides. Refer to TWTRNotificationConstants.h for a listing of the available notifications.

Implement these optional methods as needed:

tweetView:didSelectTweet:

// Objective-C
- (void)tweetView:(TWTRTweetView *)tweetView didSelectTweet:(TWTRTweet *)tweet {
  NSLog(@"Tweet selected: %@", tweet);
}
// Swift
func tweetView(tweetView: TWTRTweetView, didSelectTweet tweet: TWTRTweet) {
  print("Tweet selected: \(tweet)")
}

tweetView:didTapURL:

// Objective-C
- (void)tweetView:(TWTRTweetView *)tweetView didTapURL:(NSURL *)url {
  // Open your own custom webview
  MyWebViewController *webViewController = [MyWebViewController alloc] init];

  // *or* Use a system webview
  UIViewController *webViewController = [[UIViewController alloc] init];
  UIWebView *webView = [[UIWebView alloc] initWithFrame:webViewController.view.bounds];
  [webView loadRequest:[NSURLRequest requestWithURL:url]];
  webViewController.view = webView;

  [self.navigationController pushViewController:webViewController animated:YES];
}
// Swift
func tweetView(tweetView: TWTRTweetView!, didTapURL url: NSURL!) {
  // Open your own custom webview
  let webViewController = MyWebViewController()

  // *or* Use a system webview
  let webViewController = UIViewController()
  let webView = UIWebView(frame: webViewController.view.bounds)
  webView.loadRequest(URLRequest(url: url as URL))
  webViewController.view = webView
  self.navigationController!.pushViewController(webViewController, animated: true)
}

tweetView:didChangePlaybackState:

// Objective-C
- (void)tweetView:(TWTRTweetView *)tweetView didChangePlaybackState:(TWTRVideoPlaybackState)newState {
  switch (newState) {
    case TWTRVideoPlaybackStatePaused:
      // Do something when video is paused
      break;
    case TWTRVideoPlaybackStatePlaying:
      // Do something when video starts to play
      break;
    case TWTRVideoPlaybackStateCompleted:
      // Do something when video play is completed
      break;
    default:
      break;
  }

}

// Swift
func tweetView(_ tweetView: TWTRTweetView, didChange newState: TWTRVideoPlaybackState) {
  switch newState {
  case .paused:
    print("Do something when video is paused")
  case .playing:
    print("Do something when video starts to play")
  case .completed:
    print("Do something when video play is completed")
  }
}

Show Standalone Tweets in a Detailed View

Twitter Kit provides a view controller which shows a single Tweet. This view controller is presented automatically when a user taps on a Tweet view but the functionality can be overridden to provide finer grained control. Developers can implement the TWTRTweetViewDelegate, set themselves as the delegate for the Tweet view and implement the tweetView:shouldDisplayDetailViewController: method;

// Objective-C
- (BOOL)tweetView:(TWTRTweetView *)tweetView shouldDisplayDetailViewController:(TWTRTweetDetailViewController *)controller {
  // customize the controller to fit your needs.

  // show the view controller in a way that is appropriate for your current setup which may include pushing on a
  // navigation stack or presenting in a pop over controller.
  [self showViewController:controller sender:self];

  // return NO to tell Twitter Kit that you will present the controller on your own.
  // return YES if you want Twitter Kit to present it for you, this is the default if you don't implement this method.
  return NO;
}

// Swift
func tweetView(tweetView: TWTRTweetView, shouldDisplayDetailViewController controller: TWTRTweetDetailViewController) -> Bool {
  // customize the controller to fit your needs.

  // show the view controller in a way that is appropriate for you current setup which may include pushing on a
  // navigation stack or presenting in a pop over controller.
  self.showViewController(controller, sender:self)

  // return false to tell Twitter Kit that you will present the controller on your own.
  // return true if you want Twitter Kit to present it for you, this is the default if you don't implement this method.
  return false;
}

Alternatively, the TWTRTweetViewController can be used as a standalone view controller. You can initialize the controller with a Tweet and present it just like any other view controller.

NOTE: TwitterKit v3.0 and up do not support TWTRTweetDetailViewController.

Use Static JSON for Tweets

We also expose the option of constructing TWTRTweet objects from a standard JSON dictionary for applications that have already obtained the necessary Twitter API response via other means.

// Objective-C
// Create a single tweet model object from JSON
TWTRTweet *tweet = [[TWTRTweet alloc] initWithJSONDictionary:dictionary];

// Create an array of tweet model objects from a JSON array
NSArray *tweets = [TWTRTweet tweetsWithJSONArray:array];
// Swift
// Create a single tweet model object from JSON
let tweet = TWTRTweet(jsonDictionary: dictionary)

// Create an array of tweet model objects from a JSON array
let tweets = TWTRTweet.tweetsWithJSONArray(array)