How to create Facebook & twitter share button

This tutorial has been updated for X code 7.3 & swift 2.2

Facebook & twitter shares are very important because people like to brag about their achievements & you get free advertisement out of it. For example every time I run, I always share how much distance I ran on Facebook & on twitter. Whatever app I am using gets free advertisement out of it. And its super easy to implement in iOS. You don’t have to worry about log in. IOS 8 takes care of that for you.

1. Before using share button you need to be logged into Facebook & twitter in Settings -> Facebook or Twitter.

Screen Shot 2015-03-05 at 1.42.07 am

 

Screen Shot 2015-03-05 at 1.42.26 am

2. First lets set up the x code project as usual. Create new single view application X code project. Set the values as follows and save it on your desktop.

share button project

 

3. Go to main storyboard and select view controller. Set its size iPhone 4-inch in attribute section.

set size to 4 inches

 

 

4. Add button to main storyboard & rename it to Tweet to a friend

tweet to a friend button

 

5. Connect button to view controller swift file

connect to swift file

 

6. Import social framework by adding just one line on top

import UIKit
// 6
import Social

7. Add following code to button

    @IBAction func tweetPressed(sender: UIButton) {
        // 7
        if SLComposeViewController.isAvailableForServiceType(SLServiceTypeTwitter) {
            
            var twitterShare:SLComposeViewController = SLComposeViewController(forServiceType: SLServiceTypeTwitter)
            
            let tweet = "Check out this cool swift programming blog at blog.apoorvmote.com #swiftlang"
            
            twitterShare.setInitialText(tweet)
            
            self.presentViewController(twitterShare, animated: true, completion: nil)
            
        }
        else {
            let alert = UIAlertController(title: "Twitter Login Required", message: "Go to Settings -> twitter & login", preferredStyle: UIAlertControllerStyle.Alert)

            let okAction = UIAlertAction(title: "I Understood", style: UIAlertActionStyle.Default, handler: nil)

            alert.addAction(okAction)

            self.presentViewController(alert, animated: true, completion: nil)
           
        }
        
    }

8. Now build and run the app in iPhone 5s. To test if its working post the tweet. It would help out my blog also.

Screen Shot 2015-03-05 at 2.52.24 pm
Download X code file
Your challenge is to create facebook share as following

Screen Shot 2015-03-05 at 2.59.21 pm
Download Challenge Solution

Total 2 Votes
1

Tell us how can I improve this tutorial?

+ = Verify Human or Spambot ?