So today, keeping in the theme of posting useful code snippets that do not rely on privileged SDK calls, let me show you how to Tweet. The API itself is really simple: you provide a user name, password and a Twitter message. What complicates this from an iPhone point of view is that you can't just assemble a URL and shoot it upstream to Twitter.com. The request requires POST.
The NSURLRequest class simplifies submitting form data. You can use synchronous requests with sendSynchronousRequest: returningResponse: error:. Synchronous requests mean you don't have handle threads and partial results. Instead, you send one (blocking) call, and when it returns you have your results.
The following source code demonstrates the entire process. First, it escapes the command line arguments, embedding them into the request URL and the form body. Then it builds the actual API request. The request parameters include POST as the method and x-www-form-urlencoded for the content type. Finally, it contacts the Twitter server and checks to see whether the request went through or whether there were authentication errors.
You can read more about Twitter's API at their website. It's a very nice Web service to get started with due to its simplicity and ease-of-use.
#import <CoreFoundation/CoreFoundation.h>
#import <Foundation/Foundation.h>
#import <stdio.h>
int main(int argc, char **argv)
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
if (argc < 4)
{
printf("Usage: %s username password tweet\n", argv[0]);
exit(-1);
}
// Convert the C-String arguments into Twitter-happy escaped format
NSString *unpw = [[NSString stringWithFormat:@"%@:%@",
[NSString stringWithCString:argv[1]
encoding:NSUTF8StringEncoding],
[NSString stringWithCString:argv[2]
encoding:NSUTF8StringEncoding]]
stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *tweet = [[NSString stringWithCString:argv[3]
encoding:NSUTF8StringEncoding]
stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *body = [NSString stringWithFormat:
@"source=iTweet&status=%@", tweet];
// Establish the Twitter API request
id baseurl = [NSString stringWithFormat:
@"http://%@@twitter.com/statuses/update.xml", unpw];
NSURL *url = [NSURL URLWithString:baseurl];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest
requestWithURL:url];
if (!urlRequest)
{
printf("Error creating URL Request. Exiting.\n");
exit(-1);
}
[urlRequest setHTTPMethod: @"POST"];
[urlRequest setHTTPBody:[body dataUsingEncoding:NSUTF8StringEncoding]];
[urlRequest setValue:@"application/x-www-form-urlencoded"
forHTTPHeaderField:@"Content-Type"];
[urlRequest setValue:@"iTweet"
forHTTPHeaderField:@"X-Twitter-Client"];
// Contact Twitter and recover its response
printf("Contacting Twitter Server. This may take up to a minute.\n");
NSError *error;
NSURLResponse *response;
NSData* result = [NSURLConnection sendSynchronousRequest:urlRequest
returningResponse:&response error:&error];
if (!result)
{
printf("Submission Error : %s\n",
[[error localizedDescription] UTF8String]);
exit(-1);
}
// Check to see if there was an authentication error. If so, report it.
NSString *outstring = [[[NSString alloc] initWithData:result
encoding:NSUTF8StringEncoding] autorelease];
if ([outstring rangeOfString:@"uthentica"].location != NSNotFound)
printf("%s\n", [outstring UTF8String]);
else
printf("Done\n");
exit(0);
}
To avoid blocking, you can put that code in a method you call with performSelectorInBackground, which takes care of creating and removing a thread, while you go on to do something else.
Erica,
How exactly did you compile this...with what arguments? I can't get it to compile.
Thanks.
I personally used the open iPhone toolchain for 2.0 but the same source should work inside Xcode with both iPhone and Mac apps.
Ok...but what command do you use with the open toolchain to get it to compile correctly?
Eg:arm-apple-darwin-gcc9 tweet. c...what is the rest?
Dear Erica,
Is there a way to do the same
for a non-jailbroken Iphone...
Mine was stolen last weekend
and I really need it back
because the phone contains
highly classified information???
Kindest regards,
Eunice Lieveld
Did you try this code for tweets that have &'s in them? It fails for me. I could replace each & with the encoded form, but I was hoping that kind of shenanigans would not be necessary. But I cannot find a comprehensive url encoding API on the phone.
If I use this method, message will get truncated if I have ampersand in the message. Is there a solution for this?
Hi ,
What Does mean by tweet there?
-------------------------------------------------
NSString *tweet = [[NSString stringWithCString:argv[3]
encoding:NSUTF8StringEncoding]
stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
---------------------------------------------------
What kind of text do i have there?
plz help me asap
After creating an account on twitter and registering an application, I am still getting the "from=web" string in the message sent from the iphone. THough I am successfully able to send as well as delete a post on twitter.
But not able to resolve the "from = web" problem
Any idea, what I am missing here
Hi, Thank you for the code.
But when i am trying to update my status by passing email id and password and some message , i am unable to update my status. Otherwise with username it works fine.
Thanks,