Till today, the two most commonly used ways (without writing tediously long code) to integrate Twitter connect to your app is

The only problem I have with both these libraries is that, they are bloated. You end up adding at least 20 classes (more than 50 files in the first case and even more if you go with ShareKit).

Call me a person with Not Invented Here syndrome, but I hate adding third party code unless it offers considerable number of features that is critical to the app’s functionality. Today, when working on a code base, I deleted over 52 files that adds a functionality that allows a user to tweet “achievements” from within the app.

Deleting Twitter Sharing Code means getting rid of 52 files in your app

Deleting Twitter Sharing Code means getting rid of 52 files in your app

To me, this is a bloat. Same goes with ShareKit. You will use every single ShareKit supported social network only if you are writing a Google Reader (or any RSS reader) app or a Instapaper competitor. In most apps, Facebook and Twitter sharing is all that you need. 52 files for that, is a BLOAT.

Introducing RSOAuthEngine

RSOAuthEngine, in the words of the original author (Rodrigo Sieiro), is a ARC based OAuth engine for MKNetworkKit.

He originally posted his RSOAuthEngine on Github about a month ago. It is possibly the leanest implementation of Twitter oAuth I’ve ever seen. His sample code also contained a demo on how to use RSOAuthEngine with Twitter and with Instapaper.

The fork

Today, I forked his code and added a neat and important feature, iOS 5 Twitter Accounts support. I added a category class and a config file to his code and this is how it looks now.

RSOAuthEngine Files

RSOAuthEngine based Twitter Connect ~ 10 files

Just 10 files (3 classes and a category addition) that enables your app users to send tweets from the app.
Since MKNetworkKit provides operation freezing by default, users can send tweets even when they are offline. Those tweets are queued, frozen and sent when the connectivity is back again.

Using RSOAuthEngine

Step 1:
Clone the RSOAuthEngine fork from github. Add the RSOauthEngine code by dragging the directories RSOAuthEngine, Twitter and UIActionSheet+MKAdditions. If you are not using MKNetworkKit, you might have to add that too.

Step 2: Add the Twitter.framework and Account.Framework and weak link it. Weak linking ensures that your app doesn’t crash on devices running iOS 4 and below. If you are adding MKNetworkKit for the first time, you might want to add the related frameworks as well. See this blog post for details.

Step 3: Open RSTwitterConfigs.h and set the oAuth consumer key and consumer secret from twitter.
Fill in your callback URL. All these information should match exactly to the app you created on twitter’s website

Step 4: Initialize the RSTwitterEngine in your app delegate like this.

 self.twitterEngine = [[RSTwitterEngine alloc] initWithStatusChangedHandler:^(NSString *newStatus) {
    DLog(@"%@", newStatus);

Logging is purely optional.

Step 5: To send a tweet, set the presenting view controller of the twitter engine to the current view controller (where the “tweet/share button” is present) and call the sendTweet method.

ApplicationDelegate.twitterEngine.presentingViewController = self;
  [ApplicationDelegate.twitterEngine sendTweet:@"Hi there" withCompletionBlock:^(NSError *error) {

The magic behind the scenes

The fork I wrote automatically authenticates the user the first time you call the sendTweet:withCompletionBlock method. It presents a UIViewController with a UIWebView that shows the Twitter oAuth login page, extracts the credentials and saves it. The true magic is, on iOS 5+ devices, if the user has configured his twitter account on the Settings app, it shows the Twitter account authorization request and uses the built-in twitter account.

Accessing iOS Twitter Accounts

Accessing iOS Twitter Accounts


If the user has configured multiple twitter accounts, he sees

The code automatically shows this dialog when multiple iOS Twitter Accounts are available

The code automatically shows this dialog when multiple iOS Twitter Accounts are available

If there is exactly 1 account, that account is automatically used without further prompts.

The fallback

If there are no accounts configured or if the user is running iOS 4.3 or lower, the code falls back to traditional oAuth and shows a web view based authentication form.

Once the authentication workflow is done, the tweet is sent. Authentication information is saved and reused in subsequent calls to sendTweet:withCompletionBlock:.

The complete twitter sharing integration is done with just 3 classes. This, to me, is arguably the most leanest twitter sharing code in the Interwebs.

Fork it share it and do whatever you want. The code (both mine and Rodrigo’s) is licensed under MIT license.

On similar lines, I just finished a Facebook Sharing library


Follow me on Twitter

  • Andrey Anisimov

    Hi Mugunth, thanks for the great library! You mentioned that you finished a Facebook Sharing library. Will it be available on github?

    • MugunthKumar

      It’s not as clean as my other open source code. I usually publish it only after it reaches a certain level of bug-free ness.

  • holex

    what about the status update with media? how can I attach the media file correctly?

  • Dudeinthemirror

    Hi Muguth, thanks for this great add-on.
    I have a question for you : any plans to add OAuth2 to MKNetworkKit ?
    Also, can RSOAuthEngine be used for something other than Twitter ? Like accessing an entry point in our own server oauth implementation ? Or is there a better way ?

    Thanks in advance for your time.

  • Dudeinthemirror

     Hi, I think I found the answer to the first question in one of your API comments :)

     *  @abstract Sets the authorization header after prefixing it with a given auth type
     *  @discussion
     *    If you need to set the HTTP Authorization header, you can use this convinience method.
     *  This method internally calls addHeaders:
     *  The authType parameter is a string that you can prefix to your auth token to tell your server what kind of authentication scheme you want to use. HTTP Basic Authentication uses the string “Basic” for authType
     *  To use HTTP Basic Authentication, consider using the method setUsername:password:basicAuth: instead.
     *  Example
     *  [op setToken:@”abracadabra” forAuthType:@”Token”] will set the header value to
     *  “Authorization: Token abracadabra”
     *  @seealso
     *  setUsername:password:basicAuth:
     *  addHeaders:
    -(void) setAuthorizationHeaderValue:(NSString*) token forAuthType:(NSString*) authType;

  • Thanks for making really useful code.  However, my auth process stops after the modalview shows a call back URL pagen and modal view never dismiss..

    If I use native RSOauthengine, I don’t have issue at all, so I guess it has something to do with this fork?

    I am setting config like this.

    #define TW_CONSUMER_KEY @”CRrrewrwaaaaaaaaaaaaaaaaaaa”
    #define TW_CONSUMER_SECRET @”jHX6LrgPoNz4iaaaaaaaaaaaaaaaaaaaaaaa”

    // This will be called after the user authorizes your app
    #define TW_CALLBACK_URL @”http://lisgo.org/”I tried changing the call back url on twitter api setting as well, but no luck so far.Other than that, I realized this library crushes if I log out from twitter account on iOS settings after log in, then request sending tweet again without an account.  (It shows there is still an account on status bar at the time.)

    • MugunthKumar

      Could be. Can you explain more?

      • I posted an reply with detailed explanations yesterday,  and I got “the comment will be reviewed before it shows up” but maybe it didn’t go through?

        • MugunthKumar

          I dont think I got your comment.
          Author | Developer | Trainer
          iOS 5 Programming book
          iBooks: http://mk.sg/ibook
          Amazon: http://mk.sg/ios5book

          •  Somehow, it showed up at the below.  In the picture, the nsstrings are “myConsumerKey”, but I wrote the correct strings on build, I just changed them to that before taking the screenshot.

  • Any plan to support xAuth as well?  My app doesn’t need DM access so I want to use this cool library with xAuth.

  • Erdi Yerli

    I’m getting NSURLErrorDomain error 401 on simulator. What is problem ?

  • Bryn Bodayle

    Anything similar to this for Facebook and the new iOS 6 account option?

    • MugunthKumar

      This feature, I guess, is provided by Facebook iOS SDK 3.1

      Author | Developer | Trainer
      Preorder the iOS 6 Programming Pushing the Limits book http://mk.sg/ios6book

  • I’m getting NSURLErrorDomain error 401 on simulator and Device . What is problem ?

  • Is this code just out of date? I have had a HECK of a time getting it to work, and I’m finally at the point where I should be presented with the `RSWebViewController` and it is not displaying the web view. I hope this isn’t an abandonware project!

    Hopefully I’ll get it working again – are you accepting pull requests?

    • MugunthKumar

      Are you still supporting iOS 5 on your app? You mostly don’t have to.

    • I know, and I’d rather just rely on the native SDK, but client wants a fallback in case they haven’t linked their twitter profile using iOS.