How to create a Twitter Follow button in your iOS App

Much like the Facebook Like button we can create a Twitter Follow button. It’s easy to create a HTML button which we can load into a small UIWebView (about 40 pixels high):

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // add Twitter Follow button in a web view
    NSString *twitterFollowButton = @"<a href='https://twitter.com/versluis' class='twitter-follow-button' data-show-count='true' data-size='large'>Follow @versluis</a><script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs');</script>";
    
    [self.twitterWebView loadHTMLString:twitterFollowButton baseURL:nil];
}

The code for the button is a JavaScript snippet courtesy of Twitter. You can get your customised button code here:
https://about.twitter.com/resources/buttons#follow

We want to intercept the user action of actually following the link our button generates (it would load the Twitter website and ask users to log in) – so let’s place an invisible UIButton over the web view and action that instead:

- (IBAction)twitterButton:(id)sender {
    
    // open the Twitter App
    if (![[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"twitter://user?screen_name=versluis"]]) {
        
        // opening the app didn't work - let's open Safari
        if (![[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://twitter.com/versluis"]]) {
            
            // nothing works - perhaps we're not onlye
            NSLog(@"Nothing works. Punt.");
        }
    }
}

This code will first try to open the Twitter app and pass in the desired user profile. If it’s not successful it will try to open Safari with the user’s profile link.

Note that our web button will only be displayed if the user is online. Have a fallback image handy if the user is offline.





2 thoughts on “How to create a Twitter Follow button in your iOS App

  1. The invisible button looks like an hack to me. A delegate would be better: just set the webView’s delegate to the controller and add

    (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {

    if ([[request.URL absoluteString] hasPrefix:@”https://twitter.com/TWEET_USERNAME”]) {
    if (![[UIApplication sharedApplication] openURL:[NSURL URLWithString:@”twitter://user?screen_name=TWEET_USERNAME”]]) {
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@”https://twitter.com/TWEET_USERNAME”]];
    }
    return NO;
    }
    return YES;
    }

Leave a Reply