
Just yesterday I implemented social sharing in my new app called Sigma. Here is how I did it in two easy to follow steps.
First, I added Social.framework to my project and imported it to my view controller.
import Social
Second, I wrote this code for Twitter (it’s in Swift 3.0):
@IBAction func shareOnTwitter(_ sender: AnyObject) {
if(SLComposeViewController.isAvailable(forServiceType: SLServiceTypeTwitter)){
let tweetSheet = SLComposeViewController(forServiceType: SLServiceTypeTwitter)
tweetSheet?.setInitialText("initial text")
tweetSheet?.add(image)
tweetSheet?.add(URL.init(string: "http://yourlink.com"))
tweetSheet?.completionHandler = {(result) in
switch(result) {
// This means the user cancelled without sending the Tweet
case SLComposeViewControllerResult.cancelled:
break;
// This means the user hit 'Send'
case SLComposeViewControllerResult.done:
break;
}
}
if (tweetSheet != nil){
present(tweetSheet!, animated: true, completion: nil)
}
}else{
let alert = UIAlertController(title: "Log in to Twitter", message: nil, preferredStyle: UIAlertControllerStyle.alert)
let okAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alert.addAction(okAction)
present(alert, animated: true, completion: nil)
}
}
And this code for Facebook:
@IBAction func shareOnFacebook(_ sender: AnyObject) {
if(SLComposeViewController.isAvailable(forServiceType: SLServiceTypeFacebook)){
let fbSheet = SLComposeViewController(forServiceType: SLServiceTypeFacebook)
fbSheet?.setInitialText("initial text")
fbSheet?.add(image)
fbSheet?.add(URL.init(string: "http://yourlink.com"))
fbSheet?.completionHandler = {(result) in
switch(result) {
// This means the user cancelled without sending the Tweet
case SLComposeViewControllerResult.cancelled:
break;
// This means the user hit 'Send'
case SLComposeViewControllerResult.done:
break;
}
}
if (fbSheet != nil){
present(fbSheet!, animated: true, completion: nil)
}
}else{
let alert = UIAlertController(title: "Log in to Facebook", message: nil, preferredStyle: UIAlertControllerStyle.alert)
let okAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alert.addAction(okAction)
present(alert, animated: true, completion: nil)
}
}
That’s it!