How to create a Twitter Follow button in your iOS App

- by

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.



If you enjoy my content, please consider supporting me on Ko-fi. In return you can browse this whole site without any pesky ads! More details here.

Leave a Comment!

This site uses Akismet to reduce spam. Learn how your comment data is processed.