An iOS 7 Facebook Integration Tutorial using UIActivityViewController

PreviousTable of ContentsNext
Integrating Twitter and Facebook into iOS 7 ApplicationsiOS 7 Facebook and Twitter Integration using SLRequest


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


With the basics of the 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 user’s Facebook page, including text and an image.

Creating the Facebook Social App

Begin by launching Xcode and selecting the options to create a new iOS application based on the Single View Application template. Enter SocialApp as the product name and class prefix and set the device to iPhone.

Designing the User Interface

Navigate to the Main.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 Attributes 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 80-1:

The user interface layout for an iOS 7 Facebook integration application

Figure 80-1


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

Select the Image View object, display the Attributes Inspector and change the Mode setting to Aspect Fit. This will ensure that the aspect ratio of the image is preserved when displayed in the image view.

The next step is to constrain the size of the image view object so that it does not grow to accommodate the size of the selected image. With the image view selected in the storyboard canvas, click on the Pin button in the toolbar at the bottom of the storyboard panel to display the Add New Constraints panel. Within the panel, enable the check boxes next to the Width and Height constraints (Figure 80-2) to constrain the image view to its current dimensions:


Adding auto layout constraints

Figure 80-2


With the constraints configured, click on the Add 2 Constraints button.


Creating Outlets and Actions

In order to create the outlets and actions for the application we will, as always, 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.

Make sure that the SocialAppViewController.h file is displayed in the editor before Ctrl-clicking on the Text View object in the view and dragging 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 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 previously 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.

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;
@end

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

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 = @[(NSString *) kUTTypeImage];
        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[UIImagePickerControllerMediaType];
    [self dismissViewControllerAnimated:YES completion:nil];
    if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) {
        UIImage *image = 
              info[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 touchesBegan method:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

    UITouch *touch = [[event allTouches] anyObject];
    if ([_postText isFirstResponder] && [touch view] != _postText) {
        [_postText resignFirstResponder];
    }
    [super touchesBegan:touches withEvent:event];
}

Posting the Message to Facebook

All that remains is to implement the code to create 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 sendPost 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.

Running the Social Application

With the coding now complete, click on the Run button in the Xcode toolbar to launch the application on an iPhone device. 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 80-3:


Posting a message to a social network in iOS 7

Figure 80-3


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

The iOS 7 Facebook integration example app running

Figure 80-4


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 page. The next chapter will look in more detail at using both the Accounts and Social Frameworks to implement social network integration using the SLRequest class.


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 and Facebook into iOS 7 ApplicationsiOS 7 Facebook and Twitter Integration using SLRequest