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 = @&quot;&lt;a href=&#039;https://twitter.com/versluis&#039; class=&#039;twitter-follow-button&#039; data-show-count=&#039;true&#039; data-size=&#039;large&#039;&gt;Follow <a href='http://pinkstone.co.uk/mentions/versluis/' class='mention'>@versluis</a>&lt;/a&gt;&lt;script&gt;!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?&#039;http&#039;:&#039;https&#039;;if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+&#039;://platform.twitter.com/widgets.js&#039;;fjs.parentNode.insertBefore(js,fjs);}}(document, &#039;script&#039;, &#039;twitter-wjs&#039;);&lt;/script&gt;&quot;;
    
    [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:@&quot;twitter://user?screen_name=versluis&quot;]]) {
        
        // opening the app didn&#039;t work - let&#039;s open Safari
        if (![[UIApplication sharedApplication] openURL:[NSURL URLWithString:@&quot;https://twitter.com/versluis&quot;]]) {
            
            // nothing works - perhaps we&#039;re not onlye
            NSLog(@&quot;Nothing works. Punt.&quot;);
        }
    }
}

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.





Jay is the CEO and founder of WP Hosting, a boutique style managed WordPress hosting and support service. He has been working with Plesk since version 9 and is a qualified Parallels Automation Professional. In his spare time he likes to develop iOS apps and WordPress plugins, or draw on tablet devices. He blogs about his coding journey at http://wpguru.co.uk and http://pinkstone.co.uk.