Search code examples
iosswifttwitteroauthtwitter-oauth

Implementing Single-User OAuth on Twitter using Swift


I cannot find any pod or libraries written for Swift to implement a single-user OAuth so that I can let the iOS make POST statuses/update requests to my own account without having the users logging in.

Users don't need to log in as the tweets will be updated on my own account.

  • How can I implement this sort of Twitter-bot on iOS app using Swift?
  • Also, what should I set for the callback URL?
  • Can I set a dummy callback URL?

Solution

  • After hours of digging, I found a package which can expedite the process. It is called Swifter. You can also download the package using Cocoapods by adding pod "Swifter", :git => "https://github.com/mattdonnelly/Swifter.git"

    After downloading, add import Swifter at the top of your class file.

    Instantiate Swifter by adding the following,

    let twitter = Swifter(consumerKey: "", consumerSecret: "", oauthToken: "", oauthTokenSecret: "")
    

    The oauthToken and oauthTokenSecret can be found in your app.twitter.com page. They are your Access Token and Access Token Secret respectively. IF you don't have the access token yet, create one at the Keys and Tokens page. If you want to tweet from your own account, you need to provide the access token to allow single-user OAuth to perform actions like posting tweets.

    If you want to trigger a tweet update, just add the following in your button action closure or sort,

    twitter.postTweet(status: "Hello world",success: { status in
    
                    print("successfully tweeted! \(status.description)")
    
                }, failure: { error in
    
                    print("error tweeting! \(error)")
    
                }) 
    

    Do note that I am using Swifter 2.1.0.