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() {
        super.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)
        view.addSubview(button)
        
    }
    
    func twitterButtonPressed(sender: UIButton) {
        if SLComposeViewController.isAvailableForServiceType(SLServiceTypeTwitter) {
            let myTwitterController = SLComposeViewController(forServiceType: SLServiceTypeTwitter)
            myTwitterController.setInitialText("First tweet from my iOS app. http://studyswift.blogspot.com")
            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)
                UIApplication.sharedApplication().openURL(urlSettings!)
            }))
            
            self.presentViewController(alertController, animated:true, completion:nil)
        }
    }
    override func didReceiveMemoryWarning() {
        super.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.

2 comments:

  1. More impressive Blog!!! Its more useful for us...Thanks for sharing with us...
    big data in education
    big data education

    ReplyDelete
  2. Hi there,

    I would like to get in touch with the author of this article (E Huang). Are you looking for world class iOS app development company? Mindnotix is one of the best company for software development company.

    ReplyDelete