May 262011
 

Post to Twitter from your iPhone or iPad app using this tutorial!

This tutorial should be pretty easy to follow – I’m going to do it step by step, starting with downloading a file you will need to place in your project.

Step 1 – Grab that file here.

Step 2 – Put that file, oAuth.lua, into your project folder.

Step 3 – Make sure you put require(“oAuth”) into your code!

Step 4 – Create your app on Twitter to get your ID.

Step 5 – For the callback URL, use your website. Ie, http://techority.com

Step 6 – Copy and paste the following block of code into your project, likely on a gameover screen;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
consumer_key = "yourkeyhere"
consumer_secret = "yoursecrethere"
local access_token
local access_token_secret
local user_id
local screen_name

--your web address below can be anything from what i can make out as long as it is the same as the callback url set in twitter settings
--twitter sends the webaddress with the token back to your app and the code strips out the token to use to authorise it
--doing it this way, means the web popup closes itself - if it doesn't it means there is some kind of problem with the code
--I found that out the hard way!!

local twitter_request = (oAuth.getRequestToken(consumer_key, "http://techority.com", "http://twitter.com/oauth/request_token", consumer_secret))
local twitter_request_token = twitter_request.token
local twitter_request_token_secret = twitter_request.token_secret

local function listener(event)
print("listener")
local remain_open = true
local url = event.url

if url:find("oauth_token") then

url = url:sub(url:find("?") + 1, url:len())

local authorize_response = responseToTable(url, {"=", "&"})
remain_open = false

local access_response = responseToTable(oAuth.getAccessToken(authorize_response.oauth_token, authorize_response.oauth_verifier, twitter_request_token_secret, consumer_key, consumer_secret, "https://api.twitter.com/oauth/access_token"), {"=", "&"})

access_token = access_response.oauth_token
access_token_secret = access_response.oauth_token_secret
user_id = access_response.user_id
screen_name = access_response.screen_name
-- API CALL:
------------------------------
--change the message posted
local params = {}
params[1] =
{
key = 'status',
value = "I just scored " .. myscore .. " points on #PixelSlice! http://itunes.apple.com/us/app/pixel-slice-plus/id439509275?mt=8"
}

request_response = oAuth.makeRequest("http://api.twitter.com/1/statuses/update.json", params, consumer_key, access_token, consumer_secret, access_token_secret, "POST")
print("req resp ",request_response)
end

return remain_open
end

--this is your webpopup, change position/size as you wish
function tweetit (event)
native.showWebPopup(10, 10, 460, 360, "http://api.twitter.com/oauth/authorize?oauth_token=" .. twitter_request_token, {urlRequest = listener})
end

--I use this for testing on a mac, but lack of textfield makes it difficult for my app, i may as well use device
--you could use a random message generator for testing purposes so as to send a unique message each time,
--would let you see messages in terminal then

--system.openURL(10, 20, 300, 450, "http://api.twitter.com/oauth/authorize?oauth_token=" .. twitter_request_token, {urlRequest = listener})

--this is the bit that strips the token from the web address returned
--/////////////////////////////////////////////////////////////////////////////////////
--// RESPONSE TO TABLE
--/////////////////////////////////////////////////////////////////////////////////////
function responseToTable(str, delimeters)
local obj = {}

while str:find(delimeters[1]) ~= nil do
if #delimeters > 1 then
local key_index = 1
local val_index = str:find(delimeters[1])
local key = str:sub(key_index, val_index - 1)

str = str:sub((val_index + delimeters[1]:len()))

local end_index
local value

if str:find(delimeters[2]) == nil then
end_index = str:len()
value = str
else
end_index = str:find(delimeters[2])
value = str:sub(1, (end_index - 1))
str = str:sub((end_index + delimeters[2]:len()), str:len())
end
obj[key] = value
print(key .. ":" .. value)
else

local val_index = str:find(delimeters[1])
str = str:sub((val_index + delimeters[1]:len()))

local end_index
local value

if str:find(delimeters[1]) == nil then
end_index = str:len()
value = str
else
end_index = str:find(delimeters[1])
value = str:sub(1, (end_index - 1))
str = str:sub(end_index, str:len())
end
obj[#obj + 1] = value
print(value)
end
end
return obj
end

local twitterButton = display.newImage ("twitter.png")
twitterButton.x = 310
twitterButton.y = 280
localGroup:insert(twitterButton)

twitterButton:addEventListener("tap", tweetit)
--------------------------------------------------------------------

NOW – the above code was actually sent to me by a friend.

So those comments are not my own; but they were useful to me so they remain. I’m ashamed to say I can’t recall who sent this to me, I know it was one of a couple of you but I lost the email recently (D’oh!) and can’t provide credit. I recall you saying you didn’t need credit, however it was always my intention to give you a link – so please email me!

Step 7 – Change the key and secret to your own, then “http://techority.com” to your own website, matching that one listed in Twitter for the callback and finally modify the message. (It’s currently mine, obviously.)

Step 8 – Change the size of the pop up if you need to. My setting work well for Landscape. :)

Step 9 – Make sure you have a twitter button named “twitter.png” – or change the above code. (Note that because I’m using Director I have inserted it into my localGroup, however you will need to remove this line if not using Director to avoid errors.

Step 10 – Test it!

This should work fine, three of us have used it in the past 2 weeks and it’s worked out well for everyone.

Peach Pellen :)

PS – If you appreciate this, please, like Techority on Facebook or follow me on Twitter using the widgets to the right.

PPS – I apologize for how long it took to get this up, I’m currently juggling a million things at once!

Like this post? Subscribe to the monthly newsletter!

 

  37 Responses to “Post To Twitter From Your Application”

  1. I do not believe so, although I haven’t had a chance to look at Twitter for a bit – I hope I can do an updated tutorial on it in the near future.

  2. That looks good. But still, is there any way I can detect if the tweet has been sent, to then close the window myself?

  3. Try the method from comment #29 – this is a little outdated now I believe :)

  4. I actually just got the original code from here working:
    http://developer.anscamobile.com/forum/2010/08/16/twitter-auth
    Thanks for this code! I just have three questions:
    1. After a user has allowed my app to tweet for them, is there any way to tweet without showing the webPopup?
    2.When I push the button a second time, after the first popup closes, I am sent to a twitter webpage that says:

    Whoa there!
    The request token for this page is invalid. It may have already been used, or expired because it is too old. Please go back to the site or application that sent you here and try again; it was probably just a mistake.

    Do you know what this problem is or how to fix this?

    3. If you click “No, thanks”, the webPopup doesn’t close. Is there any way to detect if the user presses this, and then close the popup?

    Thanks for your code and your help!

  5. What would be the best way to close the above webPopup after a user has tweeted? Also, is there any word on OAuth working?

  6. Thanks Peach!
    Well..At least there is a way! I can manage with the other code for now!
    Do drop in a comment here if ever you find a solution! :)

  7. For now yeah I think that’s the way to go – although why the code from this sample isn’t working at the second, I don’t know. (I need to sit down and have a play with it but haven’t had any time today.)

    Things get far too busy this time of year!

  8. Yes I had tried that and it DID work! Still I thought it would be better if MY APP posted the tweet with oAuth and all that.. the latest method is equivalent to just logging in my browser and posting no?.. I had kept that method as a last resort.. :) Guess I will have to use that only!

  9. Hey Satheesh – I actually found some alternate code that should work, but then saw you were in a thread where it was mentioned so you may already have solved this – but did you try;

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    -- Function for URLencoding of message content
    local function escape (s)
            s = string.gsub(s, "([&=+%c])", function (c)
                            return string.format("%%%02X", string.byte(c))
                    end)
            s = string.gsub(s, " ", "+")
            return s
    end
     
    local tweetText = "This is the tweet message."
     
    local postBody = escape( tweetText )
    local theNetwork = theNetwork or "twitter" -- twitter is default
     
    --local theString = string.gsub(message, "( )", "%%20")
    if theNetwork == theNetwork or "twitter" then
            native.showWebPopup(20, 20, display.contentWidth - 40, display.contentHeight - 90, "http://twitter.com/intent/tweet?text="..postBody)
    end

    ?

  10. I have not changed the code, no – although that could be part of the problem – it’s very old code.

    Let me take a look at this later today when I’m a little more with it (just woke up) and I’ll see if I can figure out getting it working again. (I believe their is another method that may work better.)

  11. I got that error on my android device! Nexus to be exact! Don have a mac to try it out! :)
    BTW Peach did you change the code or something? I keep getting another error now and can’t pinpoint where the error is..

    Lua Runtime Error: lua_pcall failed with status: 2, error message is: ?:0: attempt to concatenate upvalue ‘?’ (a nil value)

    Atleast the last time it was some twitter authentication problem :(

  12. Hey Satheesh,

    I would do as Peter suggests and try building for device – no idea if it will run on Android or not but yeah, you’ll have to build to test. (Supposing you’re currently using the simulator.)

  13. I got that error in the Corona simulator. Have you tried building for a device or the Xcode simulator?

  14. Hi Peach,

    I know this code is not guaranteed to work on android.. Still any idea why this error occurs?

    1
     {“error”:”Could not authenticate you.”,”request”:”\/1\/statuses\/update.json”}
  15. If it’s a Twitter issue it’s likely some changes haven’t properly registered – but that normally takes less than 24 hours.

    I will try and look into it on the xcode simulator tonight if I have time.

    Peach :)

  16. That’s exactly what I’ve been doing. I’m thinking that it must be an issue with the Xcode simulator or twitter itself, so I may try it with a bunch of different accounts to see if one will work.

  17. Having tested this code very recently I know it works; possible suggestion would be to try it in an app on its own from scratch to ensure it’s working there for you as well.

  18. The twitter website says the application has read and write access, so I don’t think that’s the problem.

  19. Make sure you have permissions set to allow write access (read/write) on the Twitter end. You need permission to post tweets, it sounds like that could be the issue?

  20. Looking at my twitter settings, I see that my test app has been authorized to tweet with my account, but there still aren’t any tweets from the app.

  21. That doesn’t seem to work. When I authorize it, it doesn’t post the tweet, it just closes the window. I have hit the “authorize” button at least 10 times this morning, and the tweets still haven’t shown up on my page.

  22. See line 42 in the above code.

    When you authorize it will tweet it :)

  23. Thanks! Now the authentication code works on the XCode simulator. The one thing I couldn’t see is how to actually send a tweet. When I press the button, it just opens the popup to login and authorize. What should I change in the code to send the tweet?

  24. I don’t know whether or not this will work in the Corona simulator, I’d suggest testing it on the Xcode simulator or device.

    Should all work fine, used it in a demo about 2 weeks back.

    Peach :)

  25. Just tried it again, and got the following error:

    req resp {“error”:”Could not authenticate you.”,”request”:”\/1\/statuses\/update.json”}

  26. Thanks for the code!
    However, I get this one error:

    Syntax error: /Users/Peter/Desktop/twitterTest/main.lua:71: ‘)’ expected near ‘&’
    (My numbering is the same as yours)
    What can I do to fix this?

  27. It appears somewhere in your code you have an if statement without a “then”. Try fin.lua around line 359.

  28. =( Having an issue…Runtime error
    error loading module ‘fin’ from file ‘/Users/Kurt/Desktop/Crazy Putt/fin.lua’:
    /Users/Kurt/Desktop/Crazy Putt/fin.lua:359: ‘then’ expected near ‘&’
    stack traceback:
    [C]: ?
    [C]: ?
    [C]: in function ‘require’
    /Users/Kurt/Desktop/Crazy Putt/director.lua:42: in function ‘loadScene’
    /Users/Kurt/Desktop/Crazy Putt/director.lua:241: in function ‘changeScene’
    /Users/Kurt/Desktop/Crazy Putt/main.lua:98: in function ‘main’
    /Users/Kurt/Desktop/Crazy Putt/main.lua:102: in main chunk
    Runtime error: error loading module ‘fin’ from file ‘/Users/Kurt/Desktop/Crazy Putt/fin.lua’:
    /Users/Kurt/Desktop/Crazy Putt/fin.lua:359: ‘then’ expected near ‘&’
    stack traceback:
    [C]: ?
    [C]: ?
    [C]: in function ‘require’
    /Users/Kurt/Desktop/Crazy Putt/director.lua:42: in function ‘loadScene’
    /Users/Kurt/Desktop/Crazy Putt/director.lua:241: in function ‘changeScene’
    /Users/Kurt/Desktop/Crazy Putt/main.lua:98: in function ‘main’
    /Users/Kurt/Desktop/Crazy Putt/main.lua:102: in main chunk

    I am using the simulator..the screen is black…I get that error code….I change my website…I changed the keys…and i put oath and required it… =( any ideas?

  29. hi! i have this problem:
    …user/juego/socialnetwork/Menu/mainmenu.lua:382: attempt to concatenate upvalue ‘twitter_request_token’ (a nil value)
    stack traceback:
    [C]: ?
    …user/juego/socialnetwork/Menu/mainmenu.lua:382: in function
    ?: in function

  30. Thanks for sharing, Peach! Have you tried this on Android so far? I get:
    {“error”:”Could not authenticate you.”, “request”:”\/1\/statuses\/update.json”}
    The webpopup briefly flashes showing my twitter app, then closes and I see the above message in DDMS.
    Any idea why this can be or how to debug this?

    Thanks,
    Vitaly

    • Hey Vitaly,

      No, sorry – I have not tried it on Android and have no way of doing so at present. (That is why pretty much all my tutorials are iOS specific.)

      Sorry :( Try asking in the Corona forum. (Android sub forum.)

      Peach :)

  31. Hi Peach,

    I followed your Tutorial and it works great! However, I don’t have a game over screen, just a few buttons that appear at the end of each level. I inserted the code for Twitter at the bottom of my file and the button at the top, near all my other buttons. The problem is, on my older iPod touch 2nd generation, performance goes way down trying to start the level. Is there any reason why this could be happening? Thanks.

    • Yeah, it’s a bit demanding and on a 2g it’s going to be a problem. I haven’t used the code in ages but I recall testing it on a 3g and it being somewhat noticeable too.

      Sorry :(

  32. I don’t believe so; I’ve only tested it for iOS as that’s what my tutorials are written for.

    Peach :)

  33. Does this work on the Android platform?

 Leave a Reply

(required)

(required)

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Notify me of followup comments via e-mail. You can also subscribe without commenting.