An Example iPad iOS 5 TWTweetComposeViewController Twitter Application

From Techotopia
Jump to: navigation, search
PreviousTable of ContentsNext
Integrating Twitter into iPad iOS 5 ApplicationsPreparing and Submitting an iPad iOS 5 Application to the App Store


Purchase the fully updated iOS 10 / Swift 3 / Xcode 8 edition of this book in eBook ($19.99) or Print ($45.99) format.
iOS 10 App Development Essentials Print and eBook (ePub/PDF/Kindle) edition contains over 100 chapters. Learn more...

Buy eBook Buy Print Preview Book


As discussed in Integrating Twitter into iPad iOS 5 Applications the iOS 5 TWTweetCompose-ViewController class makes the integration of Twitter into iOS applications so easy that it can actually be harder to decide whether or not to integrate Twitter than to actually perform the integration.

Within this chapter an example application will be developed that demonstrates the steps necessary to implement Twitter functionality in an iOS 5 iPad application using the TWTweetComposeViewController class.




iPad Twitter Application Overview

In the course of this chapter an iPad application will be created that will allow the user to enter a Twitter text message, specify a URL and attach an image from the device’s camera roll and then send the message via Twitter using the TWTweetComposeViewController class.

Creating the TwitterApp Project

Begin by launching Xcode and creating a new iPad Single View Application project named twitterApp.

Once the project has been created, select the twitterApp target from the top of the project navigator panel on the left hand side of the Xcode window and select the Build Phases tab from the main panel. Underneath the Link Binary With Libraries heading click on the ‘+’ button and add Twitter.framework to the project. Since the application will also require access to the camera roll, also add the MobileCoreServices.framework library to the project.


Declaring Outlets, Actions and Variables

The application is going to require a text view component into which the Twitter message text will be typed, a text field for an option URL and an image view to preview any image selected by the user for inclusion in the tweet. In addition, a toolbar will contain buttons to select an image and preview the message. The image will be selected from the device camera roll via a popover. A variable is also needed to store a reference to the TWTweetComposeViewController. Finally, an action is needed to hide the keyboard when the background of the view is touched by the user.

Since the application will be using the UIImagePickerController class to provide access to the images in the camera roll, the view controller also needs to implement the UIImagePickerControllerDelegate and UINavigationControllerDelegate delegate protocols. Lastly, it is also necessary to import the <Twitter/TWTweetComposeViewController.h> and <MobileCoreServices/MobileCoreServices.h> files. Bringing all these requirements together results in a TwitterAppViewController.h file that reads as follows:

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

@interface twitterAppViewController : UIViewController
<UIImagePickerControllerDelegate, UINavigationControllerDelegate>

@property (nonatomic, retain) UIPopoverController *popoverController;
@property (nonatomic, retain) IBOutlet UIToolbar *toolbar;
@property (strong, nonatomic) IBOutlet UITextView *textView;
@property (strong, nonatomic) IBOutlet UITextField *tweetURL;
@property (strong, nonatomic) IBOutlet UIImageView *imageView;
@property (strong, nonatomic) TWTweetComposeViewController *tweetView;
-(IBAction)previewTweet: (id) sender;
-(IBAction)selectImage: (id) sender;
- (IBAction)backgroundTouched:(id)sender;
@end

Creating the TWTweetComposeViewController Instance

An instance of the TWTweetComposeViewController class needs to be allocated and initialized when the application starts up and assigned to the tweetView variable declared in the previous section. The application will also declare the optional completion handler and simply print out diagnostic information before dismissing the model composer controller. Finally, the button items to need to be added to the toolbar object. These steps can be implemented in the viewDidLoad method in the twitterAppViewController.m file, along with appropriate @synthesize directives:

#import "twitterAppViewController.h"

@interface twitterAppViewController ()

@end

@implementation twitterAppViewController
@synthesize tweetView, textView, tweetURL, imageView, popoverController, toolbar;
.
.
- (void)viewDidLoad
{
    [super viewDidLoad];
   
    tweetView = [[TWTweetComposeViewController alloc] init];

    TWTweetComposeViewControllerCompletionHandler 
      completionHandler = ^(TWTweetComposeViewControllerResult result)
    {
        switch (result)
        {
            case TWTweetComposeViewControllerResultCancelled:
                NSLog(@"Twitter Result: canceled");
                break;
            case TWTweetComposeViewControllerResultDone:
                NSLog(@"Twitter Result: sent");
                break;
            default:
                NSLog(@"Twitter Result: default");
                break;
        }
        [self dismissModalViewControllerAnimated:YES];
    };
    [tweetView setCompletionHandler:completionHandler];
}
.
.
@end

Implementing the Action Methods

The application has previously declared three action methods which now need to be implemented. The selectImage: action method needs to present the user with access to the device based camera roll using a UIImagePickerController instance, details of which were covered in the chapter entitled Accessing the iPad Camera and Photo Library. Within the twitterAppViewController.m file, add the selectImage method and associated delegate methods as follows:

- (void) selectImage: (id)sender
{
    if ([self.popoverController isPopoverVisible])
    {
        [self.popoverController dismissPopoverAnimated:YES];
    } else {
        if ([UIImagePickerController isSourceTypeAvailable:
             UIImagePickerControllerSourceTypeSavedPhotosAlbum])
        {
            UIImagePickerController *imagePicker = 
                  [[UIImagePickerController alloc] init];

            imagePicker.delegate = self;
            imagePicker.sourceType = 
                     UIImagePickerControllerSourceTypePhotoLibrary;
            imagePicker.mediaTypes = [NSArray arrayWithObjects: 
                    (NSString *) kUTTypeImage, nil];

            imagePicker.allowsEditing = NO;

            self.popoverController = [[UIPopoverController alloc]
                    initWithContentViewController:imagePicker];
            popoverController.delegate = (id)self;
            [self.popoverController 
                presentPopoverFromBarButtonItem:sender 
                permittedArrowDirections:UIPopoverArrowDirectionUp 
                animated:YES];
        }
    }
}

-(void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [self.popoverController dismissPopoverAnimated:true];
    NSString *mediaType = [info
                           objectForKey:UIImagePickerControllerMediaType];
    [self dismissModalViewControllerAnimated:YES];
    if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) {
        UIImage *image = 
                 [info objectForKey:UIImagePickerControllerOriginalImage];
        imageView.image = image;
    }
    else if ([mediaType isEqualToString:(NSString *)kUTTypeMovie])
    {
                // Code here to support video if enabled
    }
}

The next step is to implement the backgroundTouched method. This method will be called when the user touches the background of the view object and is responsible for ensuring that the keyboard is hidden from view so that it no longer obscures the screen content (for more detail on this topic refer to Writing iOS 5 Code to Hide the iPad Keyboard):

-(IBAction)backgroundTouched:(id)sender
{
    [textView resignFirstResponder];
    [tweetURL resignFirstResponder];
}

Finally, the code to configure and display the TWTweetComposeViewController user interface needs to be implemented in the form of the previewTweet: method:

- (void) previewTweet: (id)sender;
{
    NSURL *url = [[NSURL alloc] initWithString:tweetURL.text];

    [tweetView setInitialText:textView.text];
    [tweetView addImage:imageView.image];
    [tweetView addURL:url];
    [self presentModalViewController:tweetView animated:YES];
}

This method constructs an NSURL object from the URL string contained in text field and then assigns the text from the text view, the URL and the image in the image view to the TWTweetComposeViewController instance before displaying the compose view to the user.

Updating viewDidUnload

The final coding task involves the usual changes to the viewDidUnload method:

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

Designing the User Interface

All that remains prior to testing the application is to design the user interface and establish the action and outlet connections. Select the twitterAppViewController.xib file. Select the View canvas, display Attribute Inspector and change the background color to light gray. Drag and drop a TextView, TextField, ImageView and ToolBar onto the view canvas. Delete the default button item from the ToolBar if one is added by Xcode. Resize, position and configure the objects so that the layout approximately resembles that of Figure 62-1:


The user interface of an example iOS 5 iPad Twitter App

Figure 62-1


Drag and drop a second bar button item onto the toolbar and double click on each button in turn to change the text to Add Image and Preview Tweet respectively. Ctrl-click and drag from the Add Image button to the File’s Owner and establish a connection to the selectImage: action method. Do the same to connect the Preview Tweet button to the previewTweet method.

Ctrl-click and drag from the File’s Owner object to the text view object and select the textView outlet from the menu. Repeat this step to connect the tweetURL and imageView outlets to the text field and image view objects respectively. Also connect the toolbar outlet to the UIToolBar object. Finally select the View canvas background, display the Identity Inspector (View -> Utilities -> Show Identity Inspector) and change the object’s class from UIView to UIControl. Display the Connections Inspector and establish a connection from the Touch Down event to the backgroundTouched method of the File’s Owner.

Building and Running the Application

Since the camera roll on the iOS Simulator does not contain any images, in order to fully realize the capabilities of the application it will be necessary to install it on a physical iPad device (details of which are provided in Testing iOS 5 Apps on the iPad – Developer Certificates and Provisioning Profiles). Having provisioned, attached and selected a device, click on the Run button in the Xcode toolbar to compile and launch the application. Once running, enter a message into the text view, a URL into the text field and choose an image from the camera roll as illustrated in Figure 62-2:


The iOS 5 ipad Twitter example app running

Figure 62-2


Finally, touch the Preview Tweet button to display the TWTweetComposeViewController screen:


An iPad iOS 5 Twitter App shhwoing composer screen

Figure 62-3


If a twitter account has not previously been added to the device, follow the steps to add one, send the message and then check your Twitter account where the message should be listed after a short delay.


Purchase the fully updated iOS 10 / Swift 3 / Xcode 8 edition of this book in eBook ($19.99) or Print ($45.99) format.
iOS 10 App Development Essentials Print and eBook (ePub/PDF/Kindle) edition contains over 100 chapters. Learn more...

Buy eBook Buy Print Preview Book



PreviousTable of ContentsNext
Integrating Twitter into iPad iOS 5 ApplicationsPreparing and Submitting an iPad iOS 5 Application to the App Store