An iPhone iOS 6 Facebook Integration Tutorial using UIActivityViewController

From Techotopia
Revision as of 18:02, 19 September 2012 by Neil (Talk | contribs) (New page: With the basics of the iOS 6 Social Framework and UIActivityViewController class covered in the previous chapter, the goal of this chapter will be to create an example application designed...)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

With the basics of the iOS 6 Social Framework and UIActivityViewController class covered in the previous chapter, the goal of this chapter will be to create an example application designed to demonstrate the UIActivityViewController class in action. The end result will be an application designed to post status updates to the iPhone user’s Facebook page, including text and an image.


Contents


Creating the Facebook Social App

Begin by launching Xcode and selecting the options to create a new iPhone iOS application based on the Single View Application template. Enter SocialApp as the product name and class prefix, set the device to iPhone and select the Use Storyboards and Use Automatic Reference Counting options if they are not already selected.

Designing the User Interface

Navigate to the MainStoryboard.storyboard file in the project navigator panel and select it to load it into to the editing panel. Click on the background of the view object and change the background color to a light shade of grey using the Attribute Inspector panel.

Drag, position and configure a Text View, Image View and two Buttons on the view canvas so that the user interface reflects that illustrated in Figure 4-1:


The UI for an example iPhone iOS 6 app

Figure 4-1


Note that the sample Latin text has been removed from the text view object (select the object, display the Attribute Inspector and delete the contents assigned to the Text property).


Creating Outlets and Actions

In order to create the outlets and actions for the application we will make use of the Assistant Editor. First, select the Text View object and then display the editor using View -> Assistant Editor -> Show Assistant Editor menu option. Alternatively, it may also be displayed by selecting the center button (the one containing an image of a bow tie and tuxedo) of the row of Editor toolbar buttons in the top right hand corner of the main Xcode window.

Ctrl-click on the Text View object in the view and drag the resulting line to the area immediately beneath the @interface directive in the Assistant Editor panel. Upon releasing the line, the configuration panel will appear. Configure the connection as an Outlet named postText with a Strong storage type and click on the Connect button. Repeat the above steps to add an outlet for the Image View object named postImage.

The application will require three actions. One for each of the button objects and one for the background view that will be used to hide the keyboard when the user has finished entering text. Ctrl-click on the Select Image button and drag the resulting line to a position beneath the new outlets declared in the Assistant Editor. In the resulting configuration panel, change the Connection type to Action and name the method selectImage. Repeat this step to add an action for the Post Message button, this time naming the action sendPost.

In order to assign an action to the View object, it will need to be changed so that it is a subclass of UIControl. Click on the background of the view, display the Identity Inspector (View -> Utilities -> Show Identity Inspector) and change the object’s class from UIView to UIControl. Having changed the class, Ctrl-click on the view background and drag to a position beneath the other actions in the Assistant Editor panel and declare an action connection named hideKeyboard for the Touch Down event.

Once the connections have been established, select the SocialAppViewController.h file and further modify it to configure the class to act as an image picker delegate and to add some imports that will be required later in the tutorial:

#import <UIKit/UIKit.h>
#import <Social/Social.h>
#import <MobileCoreServices/MobileCoreServices.h>

@interface SocialAppViewController : UIViewController
<UIImagePickerControllerDelegate, UINavigationControllerDelegate>

@property (strong, nonatomic) IBOutlet UITextView *postText;
@property (strong, nonatomic) IBOutlet UIImageView *postImage;
- (IBAction)selectImage:(id)sender;
- (IBAction)sendPost:(id)sender;
- (IBAction)hideKeyboard:(id)sender;

@end

Implementing the selectImage and Delegate Methods

The purpose of the selectImage action method is to provide the user with access to photos on the device and allow one to be selected for inclusion in the Facebook post. With these requirements in mind, select the SocialAppViewController.m file, locate the selectImage stub added by the Assistant editor and modify it as follows:

- (IBAction)selectImage:(id)sender {
    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 presentViewController:imagePicker animated:YES completion:nil];
    }
}

Next, add the other image picker delegate methods so that the picker is dismissed when the user has made a selection:

#pragma mark -
#pragma mark UIImagePickerControllerDelegate

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

        _postImage.image = image;
    }
}

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

Hiding the Keyboard

When the user touches the view object in the background of the user interface, we need the keyboard to be removed from view. This will require that code be implemented in the hideKeyboard action method stub:

- (IBAction)hideKeyboard:(id)sender {
    [_postText resignFirstResponder];
}

Posting the Message to Facebook

All that remains is to implement the code to instantiate a UIActivityViewController instance, prime it with the text and image entered by the user and then post the message to the user’s Facebook page. These tasks are to be performed within the postMessage action method. Within the SocialAppViewController.m file, locate the stub for this method and modify it as follows:

- (IBAction)sendPost:(id)sender {
    NSArray *activityItems;

    if (_postImage.image != nil) {
        activityItems = @[_postText.text, _postImage.image];
    } else {
        activityItems = @[_postText.text];
    }

    UIActivityViewController *activityController =
                    [[UIActivityViewController alloc]
                    initWithActivityItems:activityItems
                    applicationActivities:nil];

    [self presentViewController:activityController
                   animated:YES completion:nil];
}

The code simply creates an array of items to be included in the post (in this case the text entered by the user and an image in the event that one was selected), creates a UIActivityViewController instance initialized with that array and presents the controller to the user.

Adding the Social Framework to the Build Phases

Whilst the coding is complete, an attempt to compile the application at this point will result in undefined symbols because the Social Framework and Mobile Core Services libraries have not yet been added to the project. Within the project navigator panel, therefore, select the SocialApp target at the top of the list and in the main panel select the Build Phases tab. In the Link Binary with Libraries category, click on the + button and in the resulting list of libraries select and add the Social.framework library. Repeat this step to also add the MobileCoreServices.framework library to the project.

Running the Social Application

With the coding now complete, click on the Run button in the Xcode toolbar to launch the application either on an iPhone device or using the Simulator environment. When the application appears, enter some text into the text area and select an image from the device (note that when using the simulator no images will be available). Touch the Post Message button to display the target selection screen shown in Figure 4-2:


iPhone iOS 6 Facebook app social network selection

Figure 4-2


Select the Facebook button to display the preview sheet (Figure 4-3) and then, assuming no changes to the post need to be made, touch the Post button to send the message to your Facebook page.


Previewing an iPhone iOS 6 Facebook posting

Figure 4-3


Summary

This chapter has worked through the creation of an example application that uses the UIActivityViewController class to post updates to the user’s Facebook. The next chapter will look in more detail at using the Accounts and Social Frameworks to implement social network integration using the SLRequest class.