ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel
  • »
  • Technology»
  • Computers & Software»
  • Computer Science & Programming»
  • Computer Programming Tutorials

iOS | Code | How-To Program an iOS Twitter App

Updated on July 20, 2012

With IOS 5 SDK Apple has introduced an API to allow a developer to incorporate a Twitter interface in their apps.The API offers two interfacing options: to get information from Twitter using Twitter extensive API by implementing the TWRequest class or sending tweets to Twitter by implementing the TWTweetComposeViewController to create a sheet.

To implement the API, create a Single View application. Add the Twitter Framework to the project by selecting the Project root in scrolling to the Linked Frameworks and Libraries section on the Summary page. Click on the plus symbol and in the search field enter twitter ( see screenshot below):

Twitter Framework in Project
Twitter Framework in Project
Add Twitter Framework
Add Twitter Framework

You will have to manually drag the inserted framework into the Frameworks group.

Add Button and IBAction

Next Open the Storyboard file and add a Button to the Canvas. To create a IBAction connection, open the Assistant Editor and drag+drop a connection from the button to the open header file. In the Popover, change the Connection to IBAction, give your connection a name. Finally change the sender action to “Touch Up Inside”.

SendATweet

Next open the ViewController file, to which we will add an import statement in the both the header and implementation files for the Twitter API. Add an instance method SendATweet to the header file.

In the implementation file implement the SendATweet instance method.

Since the TWTweetComposeViewController tweet cannot be declare as strong since it would generate a retain cycle, so we will define or implement it in our implementation file in the SendATweet.

TWTweetComposeViewController * tweetVC = [[TWTweetComposeViewController alloc] init];


Optionally you can add an URL, text and image. In our example I will an URL and initial text. Note that once the TWTweetComposeViewController is displayed, you won’t be able to change the data, only the user will be able to.

-(void) SendATweet {
 TWTweetComposeViewController * tweetVC = [[TWTweetComposeViewController alloc] init];
 tweetURL = [[NSURL alloc] initWithString:@"http://klanguedoc.hubpages.com"];
 [tweetVC addURL:tweetURL];
 [tweetVC addInitialText:@”Here is some sample text from @kevlangdo”];

Now we will load the tweetVC TWTweetComposeViewController view controller. Once the use has edited the text, location and / image they will either click on the “Send” button or the “Cancel”. We will capture these events next by calling the completionHandler method of the TWTweetComposeViewController View Controller.

[self presentViewController:tweetVC animated:YES completion:nil];

tweetVC.completionHandler = ^(TWTweetComposeViewControllerResult twResult) {
switch(twResult) {

case TWTweetComposeViewControllerResultDone:
// This means the user hit 'Send'
break;
case TWTweetComposeViewControllerResultCancelled:
// This means the user cancelled without sending the Tweet
break;
}

Once the user has taking an action, we will need to dismiss the TWTweetComposeViewController View Controller and the keyboard. We will need to call the dismissViewControllerAnimated method of the ViewController class to send the Twitter Composer to the background.

//Dismiss the TWTweetComposeViewController
dispatch_async(dispatch_get_main_queue(), ^{
[self dismissViewControllerAnimated:NO completion:nil];
});

};
}

All that is left is to add a bit of code to call the SendATweet from the IBAction button:

- (IBAction)TweetAction:(id)sender {
[self SendATweet];
}


That is it. It is so simple. The first time you run this app in the Simulator, you will need to setup your account in the App settings app in the App Settings in the Simulator.:

Setup Twitter Account in Settings in Simulator
Setup Twitter Account in Settings in Simulator
TWTweetComposeViewController
TWTweetComposeViewController

klViewController.m

//
//  klViewController.m
//  TweetThis
//
//  Created by Kevin Languedoc on 2/16/12.
//  Copyright (c) 2012 kCodebook. All rights reserved.
//

#import "klViewController.h"
#import <Twitter/Twitter.h>

@implementation klViewController
@synthesize tweetURL;


- (IBAction)TweetAction:(id)sender {
      [self SendATweet];
}

-(void) SendATweet{
    
    TWTweetComposeViewController * tweetVC = [[TWTweetComposeViewController alloc] init];
    
   // if([TWTweetComposeViewController canSendTweet]){
        tweetURL = [[NSURL alloc] initWithString:@"http://twitter.com/"];
        [tweetVC addURL:tweetURL];
        [self presentViewController:tweetVC animated:YES completion:nil];   
        
        tweetVC.completionHandler = ^(TWTweetComposeViewControllerResult twResult) {
            switch(twResult) {
                    
                case TWTweetComposeViewControllerResultDone:
                    //  This means the user hit 'Send'
                    break;
                case TWTweetComposeViewControllerResultCancelled:
                    //  This means the user cancelled without sending the Tweet
                    break;
            }
            
            //Dismiss the TWTweetComposeViewController
            dispatch_async(dispatch_get_main_queue(), ^{            
                [self dismissViewControllerAnimated:NO completion:nil];
            });
            
        };

   // }

}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
  
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.

    
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
	[super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
	[super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return YES;
}

@end

klViewController.h

//
//  klViewController.h
//  TweetThis
//
//  Created by Kevin Languedoc on 2/16/12.
//  Copyright (c) 2012 kCodebook. All rights reserved.
//

#import <UIKit/UIKit.h>
#import <Twitter/Twitter.h>

@interface klViewController : UIViewController


@property(nonatomic, strong) NSURL *tweetURL;

- (IBAction)TweetAction:(id)sender;

-(void) SendATweet;


@end
Twitter Output
Twitter Output

Comments

    0 of 8192 characters used
    Post Comment

    • profile image

      mikeydcarroll67 6 years ago

      OK. I'll look into that!

    • klanguedoc profile image
      Author

      Kevin Languedoc 6 years ago from Canada

      Yes there is a SDK on the Facebook Developer site. You have to register a Facebook App to get an id before you can implement the SDK.

    • profile image

      mikeydcarroll67 6 years ago

      App is finished and submitted, is there any way to do something similar with the Facebook framework? Like submitting a URL to a Facebook status?

    • klanguedoc profile image
      Author

      Kevin Languedoc 6 years ago from Canada

      You very welcome. The API is very easy to work with, you will enjoy it.

    • profile image

      mikeydcarroll67 6 years ago

      Thanks for posting this! I'll definitely need it!

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: "https://hubpages.com/privacy-policy#gdpr"

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)