Social media integration is not something that most apps can ignore. These days, social media integration in apps is the norm rather than the exception. Fortunately for you, Apple has integrated support for Facebook Twitter, Sina Webo, and Tecent Webo into iOS 9. Posting to social media services has never been easier!
In this lesson, you learn to integrate the Social framework in your iOS apps and allow the user to share a post on Facebook and Twitter from your apps. You can build more complex clients that can access the entire Facebook/Twitter API, but this topic is beyond the scope of this book.
The Social framework is not included in any of the standard iOS project templates that you use when creating a new project. You will need to add a reference to this framework manually. You can do this from the Project Settings page in Xcode. Select the project node in the project navigator to display the settings page. On the settings page, select the build target and switch to the Build Phases tab. Click the plus (+
) button under the Link Binary With Libraries category and select Social.framework
from the list of available frameworks (see Figure 28.1).
The Social framework provides a share sheet that you should use in your apps if all you want is a simple “share” feature. The share sheet is an instance of the SLComposeViewController
class and provides a convenient user interface to allow the user to type a message, attach an image, and add the current location (see Figure 28.2).
The keyboard is displayed automatically when the share sheet appears and disappears automatically when the user presses the Send or Cancel buttons. Creating and displaying the share sheet configured to one of the supported services is a simple matter of instantiating it and presenting it modally:
let facebookMessageComposer:SLComposeViewController =
SLComposeViewController(forServiceType: SLServiceTypeFacebook)
self.presentViewController(facebookMessageComposer,
animated: true, completion: nil)
When creating an SLComposeViewController
instance, you must provide a single argument that indicates what social media service you want to use. This argument can have one of four possible values:
SLServiceTypeTwitter
SLServiceTypeFacebook
SLServiceTypeSinaWeibo
SLServiceTypeTencentWeibo
The options displayed in the share sheet will vary depending on the social media service that is configured. Typically, you will want to do this in an action method that is triggered when your user taps on a button in the user interface. Before you show the share sheet for a particular service, you must check to see if the user has created an appropriate account on the system (see Figure 28.3).
For instance, if you detect that the user has not created a Twitter account on the system, you may want to hide the Tweet button from your user interface entirely, or display an alert when the user taps it.
To check the availability of a service, use the isAvailableForServiceType(serviceType: String!)
class method of the SLComposeViewController
class as follows:
if SLComposeViewController.isAvailableForServiceType(SLServiceTypeFacebook)
{
// service is available
}
else
{
// service is not available, perhaps show an alert to the user?
}
You can set up the initial text displayed in the tweet sheet prior to displaying it by calling the setInitialText()
method on the SLComposeViewController
instance:
func setInitialText(text: String!) -> Bool
This method takes one String
argument that contains the text you want to set and returns a Boolean value that contains the result of the operation. Common reasons why the operation may not be successful are:
You can attach an image to the share sheet by calling the addImage()
method on the SLComposeViewController
instance:
func addImage(image: UIImage!) -> Bool
This method has one argument that is a UIImage
object and returns a Boolean result. The image is automatically resized and uploaded to the appropriate social media service by the framework. You must examine the return value to determine if the operation was successful.
To add a URL to the share sheet, use the addURL()
method:
func addURL(url: NSURL!) -> Bool
As with the setInitialText()
and addImage()
methods, the addURL()
method returns a Boolean value indicating success or failure. It is important to note that images and URLs take up part of the character limit imposed by the social media service.
You can provide an optional block completion handler that will be executed when the operation has completed. Assuming messageComposer
is an instance of an SLComposeViewController
configured for Twitter, you can do this as follows:
messageComposer.completionHandler = (result:SLComposeViewControllerResult) in
// place your code here
}
Within the block, you can examine the value of the result
parameter to get more information on the result of the operation. The value of the result
parameter depends on which button was pressed by the user, and can be either of the following:
Cancelled
Done
You will need to dismiss the tweet sheet by calling the dismissModalViewControllerAnimated()
method of the presenting view controller. If you do not provide a block completion handler, the tweet sheet is dismissed automatically regardless of the result of the operation.
In this Try It, you create a simple iPhone application based on the Single View Application template called SocialTest
that displays Facebook and Twitter share sheets with pre-populated contents.
UIButton
instances to the default scene and appropriate action methods to the view controller class.ShareTest
.
Assets.xcassets
file by clicking on it in the project navigator.Images
folder in this chapter's resources from the website.Petal
.Petal_1x.jpg
, Petal_2x.jpg
, and Petal_3x.jpg
images from this chapter's resources into the appropriate placeholders in the image set.Main.storyboard
file in the Interface Editor.Table 28.1 Layout Constraints
Element | Left | Top | Right | Height |
Facebook button | 20 | 20 | 20 | 40 |
Twitter button | 20 | 20 | 20 | 40 |
ViewController.swift
file is loaded in it.ViewController.swift
file.onFacebookShare
.ViewController.swift
file is loaded in it.ViewController.swift
file.onTwitterShare
.ViewController
class:
import UIKit
import Social
ViewController.swift
file in the project explorer.onTwitterShare
method to resemble the following:@IBAction func onTwitterShare(sender: AnyObject) {
if
SLComposeViewController.isAvailableForServiceType(SLServiceTypeTwitter)
{
let twitterMessageComposer:SLComposeViewController =
SLComposeViewController(forServiceType: SLServiceTypeTwitter)
twitterMessageComposer.setInitialText("Test Twitter Post")
twitterMessageComposer.addURL(NSURL(string: "http://www.asmtechnology.com"))
twitterMessageComposer.addImage(UIImage(named: "Petal"))
self.presentViewController(twitterMessageComposer,
animated: true, completion: nil)
}
else
{
let twitterNotConfiguredAlert =
UIAlertController(title: "Twitter Not Configured",
message: "Please setup a twitter account.",
preferredStyle: UIAlertControllerStyle.Alert)
twitterNotConfiguredAlert.addAction(UIAlertAction(title: "OK",
style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(twitterNotConfiguredAlert,
animated: true, completion: nil)
}
}
ViewController.swift
file in the project explorer.onFacebookShare
method to resemble:@IBAction func onFacebookShare(sender: AnyObject) {
if
SLComposeViewController.isAvailableForServiceType(SLServiceTypeFacebook)
{
let facebookMessageComposer:SLComposeViewController =
SLComposeViewController(forServiceType: SLServiceTypeFacebook)
facebookMessageComposer.addURL(NSURL(string:
"http://www.asmtechnology.com"))
facebookMessageComposer.addImage(UIImage(named: "Petal"))
self.presentViewController(facebookMessageComposer,
animated: true, completion: nil)
}
else
{
let facebookNotConfiguredAlert =
UIAlertController(title: "Facebook Not Configured",
message: "Please setup a facebook account.",
preferredStyle: UIAlertControllerStyle.Alert)
facebookNotConfiguredAlert.addAction(UIAlertAction(title: "OK",
style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(facebookNotConfiguredAlert,
animated: true, completion: nil)
}
}