Difference between revisions of "An Example iPhone iOS 5 TWTweetComposeViewController Twitter Application"

From Techotopia
Jump to: navigation, search
m (Text replacement - "<htmlet>ezoicbottom</htmlet>" to "")
m (Text replacement - "<hr> <table border=" to "<htmlet>ezoicbottom</htmlet> <hr> <table border=")
Line 203: Line 203:
  
  
 +
<htmlet>ezoicbottom</htmlet>
 
<hr>
 
<hr>
 
<table border="0" cellspacing="0">
 
<table border="0" cellspacing="0">

Revision as of 18:11, 11 May 2016

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


Learn SwiftUI and take your iOS Development to the Next Level
SwiftUI Essentials – iOS 16 Edition book is now available in Print ($39.99) and eBook ($29.99) editions. Learn more...

Buy Print Preview Book


As discussed in Integrating Twitter into iPhone iOS 5 Applications the iOS 5 TWTweetComposeViewController 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 iPhone application using the TWTweetComposeViewController class.


Contents


iPhone Twitter Application Overview

In the course of this chapter an iPhone 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 iPhone 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 variable is needed to store a reference to the TWTweetComposeViewController instance and actions for buttons that will display the image picker and Twitter compose screen respectively. 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>
{
    UITextView *textView;
    UITextField *tweetURL;
    UIImageView *imageView;
    TWTweetComposeViewController *tweetView;
}
@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;
-(IBAction)selectImage;
- (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. These steps can be implemented in the viewDidLoad method in the twitterAppViewController.m file, along with appropriate @synthesize directives:

#import "twitterAppViewController.h"

@implementation twitterAppViewController
@synthesize tweetView, textView, tweetURL, imageView;
.
.
- (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 iPhone Camera and Photo Library. Within the twitterAppViewController.m file, add the selectImage method and associated delegate methods as follows:

- (void) selectImage
{
    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 presentModalViewController:imagePicker animated:YES];
    }
}

-(void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    NSString *mediaType = [info
         objectForKey:UIImagePickerControllerMediaType];
    [self dismissModalViewControllerAnimated:YES];
    if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) {
        UIImage *image = [info
            objectForKey:UIImagePickerControllerOriginalImage];
        imageView.image = image;
    }
}

-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [self dismissModalViewControllerAnimated:YES];
}

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 iPhone 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
{
    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.

Releasing Memory

The final coding task involves the requisite memory management tasks in the viewDidUnload method:

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    self.tweetView=nil;
    self.textView=nil;
    self.tweetURL=nil;
    self.imageView=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 and drag and drop a TextView, TextField, ImageView and two Buttons onto the view canvas. Resize, position and configure the objects so that the layout approximately resembles that of Figure 55-1:


The user interface design of the example iOS 5 iPhone Twitter app

Figure 55-1

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. Select the Preview Tweet button, display the Connections Inspector and connect the Touch Up Inside event to the File’s Owner object selecting the previewTweet action from the resulting menu. Repeat this step to connect the Select Image button to the selectImage method.

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 iPhone device (details of which are provided in Testing iOS 5 Apps on the iPhone – 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. Finally, touch the Preview Tweet button to display the TWTweetComposeViewController screen. 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.


Learn SwiftUI and take your iOS Development to the Next Level
SwiftUI Essentials – iOS 16 Edition book is now available in Print ($39.99) and eBook ($29.99) editions. Learn more...

Buy Print Preview Book



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