With the new Twitter framework it's much easier to integrate apps with this service, except when you have to run on older iOS versions. If integration is not imperative and you can skip Twitter feature for older clients you still have to write your code in a way that the app does not crash on iOS 4 or earlier.
The first step is to add Twitter framework to the project. You do it as usual but change 'Required' setting to 'Optional' so if the framework is not available the app will be able to start anyway.
Next in your view controller import <Twitter/Twitter.h> and add the following method:
- (IBAction)tweet:(NSString *)text image:(UIImage *)image {
if ([TWTweetComposeViewController canSendTweet]) {
TWTweetComposeViewController *controller =
[[[TWTweetComposeViewController alloc] init] autorelease];
[controller setInitialText:text];
if (image) {
[controller addImage:image];
}
[self presentModalViewController:controller animated:YES];
}
}
It will work on iOS 5 but won't on earlier versions and the reason is that we try to load TWTweetComposeViewController class and fail to do so. What we should do is to remove the direct reference to it and load it in a 'safe' way:
- (IBAction)tweet:(NSString *)text image:(UIImage *)image {
Class cclass = NSClassFromString(@"TWTweetComposeViewController");
if (cclass && [cclass canSendTweet]) {
id controller = [[[cclass alloc] init] autorelease];
[controller setInitialText:text];
if (image) {
[controller addImage:image];
}
[self presentModalViewController:controller animated:YES];
}
}
This second implementation will work on any iOS version. The same approach could be used in all other cases when you have to make use of some new iOS feature and stay compatible with previous releases.