TwitterAgent Tutorial : Tweet from iPhone app in one line code with auto tinyURL

1 Star2 Stars3 Stars4 Stars5 Stars (6 votes, average: 3.83 out of 5)
Loading ... Loading ...

XAuth was not used in my classes,  hope to integrate soon.
Vodkhang used the UI used in TwitterAgent with XAuth

Perhaps, you have used the FacebookAgent in your apps. I gratefully thank the fellows from  iphonedevsdk.com and other iPhone developers who mailed me saying the class helped them. These are actual inspiration of sharing code with all.

Now, I would like to share my TwitterAgent class with you. Using TwitterAgent you can now integrate twitter in your iPhone app seamlessly. Additionally, you can also specify a URL and can make it tinyURL on the fly just passing an extra parameter!

Here are the steps:

1. Download TwitterAgent and BusyAgent and add them into your project.

2. Import TwitterAgent.h in the file where we want to use

3. Now call any of these function, they are self explanatory!

[[TwitterAgent defaultAgent] twit ];

[[TwitterAgent defaultAgent] twit:@"Search with google!" ];

[[TwitterAgent defaultAgent] twit:@"Search with google!" withLink:@"http://www.google.com" makeTiny:NO];

[[TwitterAgent defaultAgent] twit:@"Search with google!" withLink:@"http://www.google.com" makeTiny:YES];

Screenshots:

Login To Twitter

You only need to login once in one session. Login information will be saved to the device and will be used next time the application starts.

[[TwitterAgent defaultAgent] twit];

[[TwitterAgent defaultAgent] twit:@"Search with google!"];

[[TwitterAgent defaultAgent] twit:@"Search with google!" withLink:@"http://www.google.com" makeTiny:NO];

[[TwitterAgent defaultAgent] twit:@"Search with google!" withLink:@"http://www.google.com" makeTiny:YES];

Hope it will come into your help. Cheers!




Add to Google Reader or Homepage


  • Ksukumarraj

    it s just to show how to tweet only it s not authenticate nd cant see in my profile too really waste 

  • Satishkumar Iphone

    hi its a good stuff.. 
    I successfully connected to twitter,  but i have problem. i want to get the tweets from the twitter account ... can you please help me in getting that.... Thanks for the above stuff...

  • Anouer Benhamouda

    help me please i need  the source code for twitter integration in iphone

  • Varunsharma57

    its not working

  • Daniel Nilsson

    how should this look like ??

    i need to add my twitter secret ??

  • Praveen351

    can anybody send me the source code for twitter integration in iphone and also google maps source code for my mail.id  praveen351@gamil.com

  • I've implemented your code library, as instructed, into my app. I login, post the tweet and, from all indications, it posts correctly. However, I never see the post on my Twitter page.

    Is this a code issue?

  • S Patel08

    I can't understand, how to use it in my app

  • please ;( can u update code for new OAuth :| ?

  • Fiona

    This project was a nice one but not working anymore as twitter requires oAuth now. Can you please modify it? Thanks.

  • petardinew

    I've postet something to twitter, the programm said that it was successful but my posting was not in twitter? Why not? Is something to be changed URL or something else?

  • thanks for trying this... but this project is not continued anymore... too busy :(

    now, this have to use oAuth.

  • Twitter

    Share on twitter doesn't work

  • yea... not oauth is required... will add an update soon.

  • itsfall

    can you tell us when you add an update?

  • Kvh

    any idea when oauth would be implemented?

  • Alaasm24

    Man love your work, would love an update to fix for oauth or xauth

  • soon, when? more or less?
    Thks

  • Yash Patel

    Aman,
    Great stuff but i have strange problem. I successfully connected to twitter, it authenticate and says that you have successfully posted but i never see post on my twitter account.

    Thanks in Advance.

    Yash

  • Rinku Sadhwani

    hello,i m having same prob do u got solution if yes then plz tell me ( I successfully connected to twitter, it authenticate and says that you have successfully posted but i never see post on my twitter account.)

    Thanks in Advance.

  • now,, it will require oAuth, curl based old service is not supported anymore.. and I am too busy to add oAuth :(

  • Anouer Benhamouda

    houw to add oAuth pleaseeeeeeeeee

  • This code is not working for me =/

    The login process is fine, it is detecting if it's a valid username and password. It posts and tells me that the tweet has been posted. But when I check twitter page nothing has changed!

    I'm using just the example project without any modifications.

    Maybe something has changed in the API?

  • Popoption

    I am having the same issue. Any ideas anyone?

  • Jeff

    Is there a version of TwitterAgent that supports oAuth?

  • Nea

    TwitterAgent is a great and simple piece of code!

    However as Jeff says Twitter has from 31 of August changed to used oAuth, thus TwitterAgent no longer works. Will you make a fix anytime soon? :)

  • SRIKANTH

    CAN U PLEASE SUGGEST ME HOW TO INTEGRATE TWITTER TO MY APP....

  • Someone

    Is it free? I mean, can I use it in my app?

  • yea all code available in this site is free.

    But most probably it won't work any more and at present I am not updating any code... busy in other projects at office :(

  • Baoust

    Tinyurl have a problem.
    When i publish, the link tinyurl always are the same :s

  • Great stuff, Aman. You really made FB & Twitter integration easy.

    That said, I ran a "Build and Analyze" and you've got a few memory leaks in your code. Any plans to address those in the future?

  • mahmud ahsan

    Awesome Aman Vai, very helpful.

  • Prithviraj

    Awesome tutorial... Really it helped me a lot.. thanks for giving us this wonderful tutorial. One thing i found is it is not handling the error if the user entered password or log in name is wrong?

  • mozymac

    Hello,

    I want to put instead of the link inside the "withLink" I want to put a string. How can I do that?

    Thank you.

  • ubers

    new issue, it seems that no matter what username and password are entered, i still login and can post. Even if the username does not exist or the password is wrong I still get to the post screen and can post.

  • kumar

    Same here. I changed my username, but it still show the old name and post on Twitter.

  • ubers

    I solved this problem if you look below by simply parsing the data received back by twitter. If the data had the word "errors" in it, I call connectionDidFailWithError with isAuthFailed = YES so that I get a UIAlert that the username/password were incorrect. if the data had the word "user" in it, I let the user login. This is a basic explanation of what I did, although I have now switched over to using OAuth for Twitter since this basic http auth won't work as of June (forget the day).

  • Kumar

    thanks Uber

    Can you upload your code with Oath here pls? It will be great help to many people.

  • ubers

    do a google search for "An example iPhone Twitter app with OAuth authentication" and usually the first item is where I got the code from. the blog is by a guy named jaanus, which it should say at the top of the page.

  • just checked it... you are right.. but no idea why its happening.. earlier I found it working.... i am totally confused.. digged for some time but no help.... please do share if you found what's happening or why not happening.
    thanks.

  • ubers

    I used this to trace what was being recieved:

    - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {

    NSString* strData = [[[NSString alloc] initWithBytes:[data bytes] length:[data length] encoding:NSASCIIStringEncoding] autorelease];
    NSLog(@"Received data: %@", strData ) ;
    return ;
    }

    It prints <error code="32">Could not authenticate you.</error>, so twitter does recognize the invalid username/password but your code does not seem to catch this. I'm still a newbie so I'm not sure how to code in something to catch this error from twitter.

  • ubers

    fixed the problem in my code, added in some xml parsing to process an error, posting code in a sec...

  • ubers

    I added this to the ".h" file:

    NSMutableData* receivedData;

    The new methods in the ".m" file are:

    - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
    {
    [receivedData setLength:0];
    }

    - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [receivedData appendData:data];

    NSXMLParser* parser = [[NSXMLParser alloc] initWithData:data];
    [parser setDelegate:self];
    [parser parse];

    return;
    }

    - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI
    qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
    {
    if ([elementName isEqualToString:@"errors"])
    {
    authenticated = NO;
    [parser abortParsing];
    }

    if ([elementName isEqualToString:@"user"])
    {
    authenticated = YES;
    [parser abortParsing];
    }
    }

    Modified methods in the ".m" file are:

    - (void)connectionDidFinishLoading:(NSURLConnection *)connection
    {
    [loading1 stopAnimating];
    [loading2 stopAnimating];

    if(authenticated == NO)
    {
    isAuthFailed = YES;
    NSError* error = [NSError errorWithDomain:NSURLErrorDomain code:1 userInfo:nil];
    [self connection:connection didFailWithError:error];
    }

    if(authenticated == YES)
    {
    isAuthFailed = NO;

    [connection release];
    [receivedData release];

    if(isLogged)
    {
    UIAlertView* aler = [[UIAlertView alloc] initWithTitle:@"Twitter" message:@"Tweet Posted!" delegate:nil cancelButtonTitle:@"Close" otherButtonTitles:nil];
    [aler show];
    [aler release];

    [self login];
    }

    else
    {
    twitterWindow.hidden = YES;
    twitterWindow2.hidden = NO;
    isLogged = YES;
    [[NSNotificationCenter defaultCenter] postNotificationName:@"notifyTwitterLoggedIn" object:nil userInfo:nil];
    }
    }
    }

    Also, "authenticated" is just a simple BOOL I added to the ".m" file.

  • ubers

    Oh btw, I changed it so my twitter appears through windows instead of view alerts, if anyone wants the code for that (it's easy to do really) gimme your email and i'll send it over :-)
    Guess I should look into OAuth now since basic http auth for Twitter won't work come June...

    EDIT: forgot, in "OnLogin" you want to make an else statement for "if(!theConnection)" which says:
    "receivedData = [[NSMutableData data] retain];"
    Do the same thing for "OnSend"

  • kumar

    Hi Aman, first of all, this is a great help. Thanks.

    Just 1 error i found, when i run the app with performance tool, i find 1 error which say "xagents_twitter_conifg_file.plist" not found. TweeterAgent.m has reference to this file. pls. advise.

  • hey Kumar,
    thanks for using and reporting this issue :)

    that was a typo which was fixed in the latest code.

    in twitteragent.m, you find a define of XAGENT_TWITTER_CONFIG_FILE...

    update that line with this:
    #define XAGENTS_TWITTER_CONFIG_FILE DOC_PATH(@"xagents_twitter_conifg_file.plist")

    hope that solves.

  • kumar

    hi Aman,

    First of all, it is great help, thanks.

    When i run the program with performance tool, i get the error that "xagents_twitter_conifg_file.plist file not found. The file TwitterAgent.m refer to this plist file. pls. advise.

  • Hi Aman, excellent code man! Thanks very much for sharing :)
    I have one problem though - I could not find in the code what's the license of this libraries? How does it go if I want to use the TwitterAgent in a commercial app ?

    Thanks, Marin

  • Whatever license suits you best :D

  • You're awesome :) Will post an article about the Twitter agent on my site when I get 10 minutes

  • I will really appreciate that... you have a cool blog!

  • bunnyhero

    does this use basic http authentication?

  • yea

  • Alaa Nassef

    Basic Authentication is going not going to be supported as of June 30, 2010. Are you planning to start using OAuth in twitter agent?

  • Jeff

    Thanks for this awesome tool. As of today, basic authentication is no longer supported. When will TwitterAgent use oAuth?

  • Jackie

    When you use landscape mode, and when you click into the textview to edit message, then the keyboard will pop up and will cover the "send"button. However, there is no way to dismiss it after finishing edit. I tried to figure that out. And you may have a try.
    In the following function:
    - (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    const char* str = [text UTF8String];

    int s = str[0];
    if(s!=0){

    if((range.location + range.length) > maxCharLength){
    return NO;
    }
    else{
    int left = 139 - ([sharedLink length] + [textView.text length]);
    lblCharLeft.text= [NSString stringWithFormat:@"%d",left];
    if([text isEqualToString:@"\n"]){

    [textView resignFirstResponder];
    return FALSE;

    }
    else {
    return YES;
    }
    }
    }

    int left = 139 - ([sharedLink length] + [textView.text length]);
    lblCharLeft.text= [NSString stringWithFormat:@"%d",left];
    return YES;
    }

  • You might also want to allow the backspace character:

    if (range.length == 1) return YES;

  • thanks for the fix :)
    plz check http://code.google.com/p/iphon...

  • Vic

    This is great piece of code. When I integrate it in my App, the user selects "post to twitter", I call the twit:withLink:makeTiny: method which logs the user in and posts the tweets. Now the users stays logged in. I would like to allow the user to logout also. The user may want to log out of that account and log in to another account for a future tweet. Is there a way to add a Logout button on the "tweet this post" view?

  • Thanks Vic for using it.

    I was thinking the same about logout! I will be adding soon, if you do this in the meantime, I will really appreciate if you share.

    Thanks.

  • Rob

    Is there anyway to include an image in the tweet? like from a screen shot?

  • no, not yet

  • Rob

    Thanks for the quick reply. Back to the drawing board. But this is a great drop in group of code. Thanks for your hard work.

  • leo888

    FacebookAgent and TwitterAgent are very cool,
    Is very easy to use, packaged very well.
    Thank you for sharing such a good code, so that Facebook and Twitter's programming has become so relaxed and happy.

    Very much hope that TwitterAgent can easily upload Image, hope to see even better updates, Thanks again.

  • thanks leo :)

  • uriash

    Wow!
    I don't have enough words to thank you for these great agents! You are one of a kind! I really mean it.
    Now a tiny question: when the user edits the text field of the tweet, how can he get out of edit mode and turn the keyboard down? the return button didn't work for me (it just jumped to the next line) and there was no "done" button.

  • Thank you for your generosity, I'm very happy that it came into your help.

    yea, u r right, but there is a "send" button on the alert box, need to tap the "send" button when done.

  • uriash

    True, but in a landscape environment you can't reach the "send" button cause it is obscured by the keyboard..

  • oops! I didn't test on landscape mode. Currently I'm fully busy in developing our next game at playdom.... dunno when i can manage time to work on this :( If you find a solve, please share.

  • exe

    Thanks! This is really helpful!
    One little possible bug: in makeTiny, url create from stringWithFormat seems miss one percent symbol?

  • thanks. And big thanx for identifying the bug :)

  • Hey, Thank you very much!
    Can you post a sample for this project? because the
    defaultAgent doesn't seems to be in here.

    Thanks.

  • seems answered the same person ( here and there ) :)

  • A sample project: http://amanpages.com/wordpress/wp-content/uploa...

    Another person in iphonedevsdk also faced the same prob.. while adding the TwitterAgent and BusyAgent folders, you have to select copy.

    Let me know if there is still any problem.
    Thanks :).

  • Jabroni

    This is outstanding, One question. Is there a way you can default the text and not allow the user to change it?

  • hi Jabroni, thanks :)

    At this moment its not possible. It will be there just after a while if you tell me the use case:

    1. user taps "share with twitter"
    2. logs in.
    3. The message will be shown to the user in alert but not in textarea i.e. not-editable. Tapping send button will send, cancel cancels.

    or

    1. user taps "share with twitter"
    2. logs in.
    3. No alert, only gray busy overlay. Posts the twit in background?

    or

    Both?

    Thank you for your suggestion. I will integrate it just let me know.

  • ubers

    newbie question, is it possible to make it so that the twitter menus are portrait mode through code and if so, how? (program comes though unity so I cannot change the plist settings).

  • not clear what do wanted to mean... it is in portrait mode... can you elaborate?

  • ubers

    if i hold the device horizontally (landscape, home button to the right) the twitter login menu rotates to that orientation. If i hold the device vertically (home button on the bottom) the login menu rotates to that orientation. I want the menu to only be in the vertical orientation and not have it adjust when I turn the device (when horizontal, the keyboard covers up where you are putting your tweet and you cannot see what you are typing). Hope that clarifies what I mean.

  • .. crystal clear :)

    no, not possible. Just tried it. I have rotated the alert view -90 degrees so it appears as it should be on portrait mode right but the keyboard orientation remains landscape...

    btw, if you checkout the latest code from google code, you will get a fix.. now while typing twit message if the user presses 'enter' key, keyboard disappears. that may help.

    thanks :)

  • Guest

    ok, thanks though. the code is great regardless. maybe someday twitter @anywhere will get iphone support so we don't run into this problem but your stuff is an awesome solution in the meantime. thanks a bunch!

  • yea, twitter should release something like Facebook connect.

    Thanks for your comment.

  • Faiz Rasool

    And one more thing Aman!!
    I have posted the tweets with user locations. In my code self.myFamilyMap.fLatitude & self.myFamilyMap.fLongitude are the values of latitude and longitude respectively.
    my app was using a map to locate the family members , so variable names are depicting map for family :-)

blog comments powered by Disqus