An iOS 8 Swift Facebook Integration Tutorial using UIActivityViewController

From Techotopia
Revision as of 20:39, 1 February 2016 by Neil (Talk | contribs) (Text replacement - "<google>BUY_IOS8</google>" to "<htmlet>ios9_upgrade</htmlet>")

Jump to: navigation, search
PreviousTable of ContentsNext
Integrating Twitter and Facebook into iOS 8 Applications using SwiftiOS 8 Facebook and Twitter Integration using SLRequest and Swift


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.


Contents


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 set the Device and Language menus to Universal and Swift respectively.

Designing the User Interface

Navigate to the Main.storyboard file in the project navigator panel and select it to load it into Interface Builder. 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 Toolbar onto the view canvas. Drag and drop an additional Bar Button Item onto the Toolbar and set the text on the two items so that the user interface reflects that illustrated in Figure 91-1:


Ios 8 social app ui.png

Figure 91-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.

Select the Text View object, display the Auto Layout Pin menu and set Spacing to nearest neighbor constraints on all four sides of the view with the Constrain to margins option enabled. Select the Image View and repeat this step, this time also enabling the Height constraint on the view.

Finally, select the Toolbar view and set Spacing to nearest neighbor constraints of zero on the left, right and bottom edges of the view with the Constrain to margins option disabled.


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 Assistant Editor.

Make sure that the ViewController.swift 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 class declaration 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. Click on the Select Image button (noting that it may be necessary to click on it a second time since the first click will select the parent Toolbar view) and Ctrl-click and drag the resulting line to a position beneath the viewDidLoad method 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 ViewController.swift 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
import Social
import MobileCoreServices

class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

    @IBOutlet weak var postText: UITextView!
    @IBOutlet weak var postImage: UIImageView!

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 ViewController.swift file, locate the selectImage stub added by the Assistant Editor and modify it as follows:

@IBAction func selectImage(sender: AnyObject) {
    let imagePicker = UIImagePickerController()
    imagePicker.delegate = self
    imagePicker.sourceType = 
		UIImagePickerControllerSourceType.PhotoLibrary
    imagePicker.mediaTypes = [kUTTypeImage as NSString]
    imagePicker.allowsEditing = false
    self.presentViewController(imagePicker, animated: true, 
		completion: nil)
}

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

func imagePickerController(picker: UIImagePickerController, 
   didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
    self.dismissViewControllerAnimated(true, completion: nil)
    let image = info[UIImagePickerControllerOriginalImage] as! UIImage
    postImage.image = image
}

func imagePickerControllerDidCancel(picker: 
	UIImagePickerController) {
    self.dismissViewControllerAnimated(true, 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:

override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
    postText.endEditing(true)
}

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 ViewController.swift file, locate the stub for this method and modify it as follows:

@IBAction func sendPost(sender: AnyObject) {

    var activityItems: [AnyObject]?
    let image = postImage.image

    if (postImage.image != nil) {
        activityItems = [postText.text, postImage.image!]
    } else {
        activityItems = [postText.text]
    }

    let activityController = UIActivityViewController(activityItems: 
		activityItems!, applicationActivities: nil)
    self.presentViewController(activityController, animated: true, 
		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 a device or simulator. When the application appears, enter some text into the text area and select an image from the device. Touch the Post Message button to display the target selection screen shown in Figure 91-2:

Ios 8 select post destination.png

Figure 91-2


Select the Facebook button to display the preview sheet (Figure 91 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.


Ios 8 preview facebook post.png

Figure 91-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 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 8 Applications using SwiftiOS 8 Facebook and Twitter Integration using SLRequest and Swift