Saturday, December 19, 2015

SLServiceTypeTwitter - Tweet from an iOS App

I have posted a tweet with the following code:

import UIKit
import Social

class ViewController: UIViewController {
    override func viewDidLoad() {
        let button = UIButton(frame: CGRectMake(70, 100, 200, 20))
        button.setTitle("twitter", forState: UIControlState.Normal)
        button.setTitleColor(UIColor.blueColor(), forState: UIControlState.Normal)
        button.setTitleColor(UIColor.cyanColor(), forState: UIControlState.Highlighted)
        button.addTarget(self, action: "twitterButtonPressed:", forControlEvents: UIControlEvents.TouchUpInside)
    func twitterButtonPressed(sender: UIButton) {
        if SLComposeViewController.isAvailableForServiceType(SLServiceTypeTwitter) {
            let myTwitterController = SLComposeViewController(forServiceType: SLServiceTypeTwitter)
            myTwitterController.setInitialText("First tweet from my iOS app.")
            presentViewController(myTwitterController, animated: true, completion: nil)
        } else {
            let alertController = UIAlertController(title: "", message: "Please login to Twitter.", preferredStyle: UIAlertControllerStyle.Alert)
            alertController.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: { action in
                //Open Settings
                let urlSettings = NSURL(string: UIApplicationOpenSettingsURLString)
            self.presentViewController(alertController, animated:true, completion:nil)
    override func didReceiveMemoryWarning() {


Strangely, this code worked without the Twitter app installed on my iPad. After the Twitter app was installed, the tweet  was no longer posted successfully, but stored in the drafts folder of the Twitter app.

No comments:

Post a Comment