Show Tweets
Note
Tweets can be rendered using user authentication or guest authentication. See Log in with Twitter.
Display a Single Tweet
To show a single Tweet, you first need to load that Tweet from the network (see Access Twitter’s 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 would like to render Tweets in a UITableView
, please see the Show a UITableView
of Tweets.
If you have stored Twitter API responses you can also construct Tweet model objects from static JSON (see Using Static JSON for Tweets, below).
1. Import the Twitter kit framework
// Swift import TwitterKit
// Objective-C #import <TwitterKit/TwitterKit.h>
2. Load Tweets from the network, then create TWTRTweetView
in completion block
// Swift Twitter.sharedInstance().logInGuestWithCompletion { session, error in if let validSession = session { Twitter.sharedInstance().APIClient.loadTweetWithID("20") { tweet, error in if let t = tweet { self.tweetView.configureWithTweet(t) } else { println("Failed to load Tweet: \(error.localizedDescription)") } } } else { println("Unable to login as guest: \(error.localizedDescription)") } }
// Objective-C __weak typeof(self) weakSelf = self; [TwitterKit logInGuestWithCompletion:^(TWTRGuestSession *guestSession, NSError *error) { if (session) { // Loading public Tweets do not require user auth [[[Twitter sharedInstance] APIClient] loadTweetWithID:@"20" completion:^(TWTRTweet *tweet, NSError *error) { if (tweet) { [weakSelf.tweetView configureWithTweet:tweet] } else { NSLog(@"Failed to load tweet: %@", [error localizedDescription]); } }]; } else { NSLog(@"Unable to log in as guest: %@", [error localizedDescription]); } }];
Tweet View Style
There are two different styles for Tweet views: TWTRTweetViewStyleRegular
and TWTRTweetViewStyleCompact
. Regular Tweet views show large images and have a “Share Tweet” button, whereas compact Tweet views are designed to be put inside tableviews through the TWTRTweetTableViewCell
(see Show a UITableView of Tweets
).
Configuring 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.yellowColor() tweetView.backgroundColor = UIColor.blueColor()
2. 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.yellowColor() TWTRTweetView.appearance().backgroundColor = UIColor.blueColor() TWTRTweetView.appearance().linkTextColor = UIColor.redColor()
Show a UITableView of Tweets
TWTRTweetTableViewCell
may be used to display Tweet views in a table view.
// Objective-C // TweetTableViewDemoViewController.m #import <TwitterKit/TwitterKit.h> #import "TweetTableViewDemoViewController.h" static NSString * const TweetTableReuseIdentifier = @"TweetCell"; @interface TweetTableViewDemoViewController () <TWTRTweetViewDelegate> @property (nonatomic, strong) NSArray *tweets; // Hold all the loaded tweets @end @implementation TweetTableViewDemoViewController - (void)viewDidLoad { [super viewDidLoad]; NSArray *tweetIDs = @[@"20", // @jack's first Tweet @"510908133917487104" // our favorite Bike tweet ]; // Setup tableview self.tableView.estimatedRowHeight = 150; self.tableView.rowHeight = UITableViewAutomaticDimension; // Explicitly set on iOS 8 if using automatic row height calculation self.tableView.allowsSelection = NO; [self.tableView registerClass:[TWTRTweetTableViewCell class] forCellReuseIdentifier:TweetTableReuseIdentifier]; // Load tweets __weak typeof(self) weakSelf = self; [[[Twitter sharedInstance] APIClient] loadTweetsWithIDs:tweetIDs completion:^(NSArray *tweets, NSError *error) { if (tweets) { typeof(self) strongSelf = weakSelf; strongSelf.tweets = tweets; [strongSelf.tableView reloadData]; } else { NSLog(@"Failed to load tweet: %@", [error localizedDescription]); } }]; } # pragma mark - UITableViewDelegate Methods - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return [self.tweets count]; } - (TWTRTweetTableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { TWTRTweet *tweet = self.tweets[indexPath.row]; TWTRTweetTableViewCell *cell = (TWTRTweetTableViewCell *)[tableView dequeueReusableCellWithReuseIdentifier:TweetTableReuseIdentifier forIndexPath:indexPath]; [cell configureWithTweet:tweet]; cell.tweetView.delegate = self; return cell; } // Calculate the height of each row - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { TWTRTweet *tweet = self.tweets[indexPath.row]; return [TWTRTweetTableViewCell heightForTweet:tweet width:CGRectGetWidth(self.view.bounds)]; } @end
// Swift import TwitterKit class TweetTableViewDemoViewController: UITableViewController, TWTRTweetViewDelegate { let tweetTableReuseIdentifier = "TweetCell" // Hold all the loaded Tweets var tweets: [TWTRTweet] = [] { didSet { tableView.reloadData() } } let tweetIDs = ["20", // @jack's first Tweet "510908133917487104"] // our favorite bike Tweet override func viewDidLoad() { // Setup the table view tableView.estimatedRowHeight = 150 tableView.rowHeight = UITableViewAutomaticDimension // Explicitly set on iOS 8 if using automatic row height calculation tableView.allowsSelection = false tableView.registerClass(TWTRTweetTableViewCell.self, forCellReuseIdentifier: tweetTableReuseIdentifier) // Load Tweets Twitter.sharedInstance().APIClient.loadTweetsWithIDs(tweetIDs) { tweets, error in if let ts = tweets as [TWTRTweet] { self.tweets = ts } else { println("Failed to load tweets: \(error.localizedDescription)") } } } // MARK: UITableViewDelegate Methods override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.tweets.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let tweet = tweets[indexPath.row] let cell = tableView.dequeueReusableCellWithIdentifier(tweetTableReuseIdentifier, forIndexPath: indexPath) as TWTRTweetTableViewCell cell.tweetView.delegate = self return cell } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { let tweet = tweets[indexPath.row] return TWTRTweetTableViewCell.heightForTweet(tweet, width: CGRectGetWidth(self.view.bounds)) } }
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:
// MyViewController.h #import <TwitterKit/TwitterKit.h> @interface MyViewController : UIViewController <TWTRTweetViewDelegate> @end // MyViewController.m @implementation MyViewController : UIViewController <TWTRTweetViewDelegate> // My stuff @end
Implement these optional methods as needed:
tweetView:didSelectTweet:
- (void)tweetView:(TWTRTweetView *)tweetView didSelectTweet:(TWTRTweet *)tweet { NSLog(@"log in my app that user selected tweet"); }
// Swift func tweetView(tweetView: TWTRTweetView!, didSelectTweet tweet: TWTRTweet!) { println("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(NSURLRequest(URL: url)) webViewController.view = webView self.navigationController!.pushViewController(webViewController, animated: true) }
tweetView:willShareTweet:
// Objective-C - (void)tweetView:(TWTRTweetView *)tweetView willShareTweet:(TWTRTweet *)tweet { // Log to my analytics that a user started to share a tweet NSLog(@"Tapped share for tweet: %@", tweet); }
// Swift func tweetView(tweetView: TWTRTweetView!, willShareTweet tweet: TWTRTweet!) { println("Tapped share for tweet: \(tweet)") }
tweetView:didShareTweet:withType:
// Objective-C - (void)tweetView:(TWTRTweetView *)tweetView didShareTweet:(TWTRTweet *)tweet withType:(NSString *)shareType { // Log to to my analytics that a user shared a tweet NSLog(@"Completed share: %@ for tweet: %@", shareType, tweet); }
// Swift func tweetView(tweetView: TWTRTweetView!, didShareTweet tweet: TWTRTweet!, withType shareType: String!) { println("Completed share: \(shareType) for tweet: \(tweet)") }
tweetView:cancelledShareTweet:
- (void)tweetView:(TWTRTweetView *)tweetView cancelledShareTweet:(TWTRTweet *)tweet { // Log to to my analytics that a user cancelled a share NSLog(@"Cancelled share for tweet: %@", tweet); }
// Swift func tweetView(tweetView: TWTRTweetView!, cancelledShareTweet tweet: TWTRTweet!) { println("Cancelled share for tweet: \(tweet)") }
Using 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)