Apr 212011
 

The below code is used to post a message to your user’s Facebook wall.

This code was taken directly from the sample provided by Ansca – I didn’t create it and my only goal is to help out those of you who haven’t been able to get wall posting to work from your iPhone apps since this latest update.

My only minor alterations are to make this easy for you to copy and paste. It’s messy, it’s got unneeded chunks in it and it’s by no means the best way of doing this – however it works perfectly and at the end of the day I don’t want to leave you guys hanging for a week while I try to find time to make a nice little snippet for you. (I will do that in time, just not right now.)

Follow the steps;

1. Copy json.lua and TableView.lua from the Facebook sample. (Applications, Corona, Sample Code, Networking, Facebook.) Put them in your project folder.

2. Paste the below code into your project.

3. Ensure your project folder has an image in it called “facebook.png”

4. Change APP ID to your own APP ID.

5. Replace my “Boyfriend Grade” specs with your own message, url, image, etc. (Don’t judge me based on that app. Please.)

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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
------------------------------------------------------------------
--                            FACEBOOK                            --
------------------------------------------------------------------

-- Facebook Commands
local fbCommand            -- forward reference
local LOGOUT = 1
local SHOW_DIALOG = 2
local POST_MSG = 3
local POST_PHOTO = 4
local GET_USER_INFO = 5
local GET_PLATFORM_INFO = 6
------------

local function printTable( t, label, level )
if label then print( label ) end
level = level or 1
if t then
for k,v in pairs( t ) do
local prefix = ""
for i=1,level do
prefix = prefix .. "\t"
end

print( prefix .. "[" .. tostring(k) .. "] = " .. tostring(v) )
if type( v ) == "table" then
print( prefix .. "{" )
printTable( v, nil, level + 1 )
print( prefix .. "}" )
end
end
end
end

----------------------------------------------------------------

local function callFacebook (event)
if ( "session" == event.type ) then
-- event.phase is one of: "login", "loginFailed", "loginCancelled", "logout"
if event.phase ~= "login" then
-- Exit if login error
return
end

-- The following displays a Facebook dialog box for posting to your Facebook Wall
if fbCommand == SHOW_DIALOG then
facebook.showDialog( {action="stream.publish"} )
end

-- Request the Platform information (FB information)
if fbCommand == GET_PLATFORM_INFO then
facebook.request( "platform" )        -- **tjn Displays info about Facebook platform
end

-- Request the current logged in user's info
if fbCommand == GET_USER_INFO then
facebook.request( "me" )
--            facebook.request( "me/friends" )        -- Alternate request
end

-- This code posts a photo image to your Facebook Wall
--
if fbCommand == POST_PHOTO then
local attachment = {
name = "Developing a Facebook Connect app using the Corona SDK!",
link = "http://developer.anscamobile.com/forum",
caption = "Link caption",
description = "Corona SDK for developing iOS and Android apps with the same code base.",
picture = "http://developer.anscamobile.com/demo/Corona90x90.png",
actions = json.encode( { { name = "Learn More", link = "http://anscamobile.com" } } )
}

facebook.request( "me/feed", "POST", attachment )        -- posting the photo
end

-- This code posts a message to your Facebook Wall
if fbCommand == POST_MSG then
local postMsg = {
message = "I just got my boyfriend grade! I scored " .. testscore .. "% on Boyfriend Grade!",
name="How do you think YOU compare to me?",
caption="Get your grade now by downloading Boyfriend Grade for your iPhone!",
link="http://itunes.apple.com/us/app/boyfriend-grade/id421597972?mt=8",
picture="http://peachpellen.com/bg75.png"
}

facebook.request( "me/feed", "POST", postMsg )        -- posting the message
end
-----------------------------------------------------------------------------------------

elseif ( "request" == event.type ) then
-- event.response is a JSON object from the FB server
local response = event.response

if ( not event.isError ) then
response = json.decode( event.response )

if fbCommand == GET_USER_INFO then
statusMessage.textObject.text = response.name
printTable( response, "User Info", 3 )
print( "name", response.name )

elseif fbCommand == POST_PHOTO then
printTable( response, "photo", 3 )
statusMessage.textObject.text = "Photo Posted"

elseif fbCommand == POST_MSG then
printTable( response, "message", 3 )
statusMessage.textObject.text = "Message Posted"

else
-- Unknown command response
print( "Unknown command response" )
statusMessage.textObject.text = "Unknown ?"
end

else
-- Post Failed
statusMessage.textObject.text = "Post failed"
printTable( event.response, "Post Failed Response", 3 )
end

elseif ( "dialog" == event.type ) then
-- showDialog response
--
print( "dialog response:", event.response )
statusMessage.textObject.text = event.response
end
end
---------------------------------------------------------------------------------------------------
-- NOTE: To create a mobile app that interacts with Facebook Connect, first log into Facebook
-- and create a new Facebook application. That will give you the "API key" and "application secret"
-- that should be used in the following lines:

local appId  = "00000000000"    -- Add  your App ID here in quotes
local apiKey = nil    -- Not needed at this time

if ( appId ) then
local function postmymsg (event)
fbCommand = POST_MSG
facebook.login( appId, callFacebook, {"publish_stream"} )
end

local fbButton = display.newImage ("facebook.png")
fbButton.x = 100
fbButton.y = 420
localGroup:insert(fbButton) -- Remove this line if not using Director
fbButton:addEventListener("tap", postmymsg)
end

Then you’re done! Build and test. This should work perfectly. (If you need help on the Facebook end check out the previous Facebook tutorial, now depreciated.)

I know this is not a good tutorial, it’s not even a real tutorial – it’s just to get those of you who are stuck at this point with Facebook up and going.

On an important side note:

For personal reasons, I may disappear for a few days sometime in the next few weeks. (I don’t know when.) I would ask that if I am clearly not online (FB, Twitter, here, etc.) that you try not to email me if possible; I wont have access and so coming back to a bunch of emails could be a tad overwhelming.

Thanks in advance for your understanding.

I hope everyone has a happy and safe Easter and that although this “tutorial” is lousy as an actual tutorial that it will still help those of you waiting on Facebook posting to publish your app move forward now.

Lastly, I know it’s been a slow month with tutorials – various things have effected this, both personal and professional and I hope that shortly this will change; but bear with me in the meantime – I have some exciting stuff planned for the not too distant future.

Peach Pellen :)

Like this post? Subscribe to the monthly newsletter!

 

  24 Responses to “Updated Facebook Tutorial For iPhone”

  1. No worries, I will update my Facebook code in the near future, I swear!

  2. Hey Peach, I am using 2011.704

    I used the sample Facebook code included with my version of Corona SDK and it is working great so far! Thanks a bunch!

  3. Hey Peach, I tried adding this to my game and I get

    “attempt to index global ‘facebook’ (a nil value)” while running the simulator. The button is unresponsive when running a compiled version on my Android.

    I also tried compiling and running the Facebook Connect application on my Android phone and, although the login box would appear, the post photo/post msg/show dialog buttons are unresponsive.

    Has the process to integrate Facebook changed at all?

    Thanks,
    Andrew

    • What version of Corona are you using? There should be an up to date sample in CoronaSDK > SampleCode on your computer. Unfortunately Facebook changes from time to time and if it has done so again recently (which it very well could have done) then yeah, this will be out of date.

  4. Did you copy json and tableview and require them and require facebook? (No facebook file should be in the project folder.)

    If so compile and it should work fine – it isn’t made for the Corona simulator and will not work in there. Try xCode simulator.

  5. ok, this part should work!

    i’m just getting this error from terminal, something wrong when I touch fbButton..it doesn’t do anything and I get this:
    Runtime error
    /Hello World/Daily Fortune/final.lua:388: attempt to index global ‘facebook’ (a nil value)
    stack traceback:
    Hello World/Daily Fortune/final.lua:388: in function
    ?: in function
    referring to this:

    1
    2
    3
    4
    5
    if ( appId ) then
    local function postmymsg (event) -- line 386
        fbCommand = POST_MSG
        facebook.login( appId, callFacebook, {"publish_stream"} -- line 388
    end

    I’m not sure what it means..

  6. Do a random function like above but with URLs, then do;

    1
    myImage = randomImage

    (Keep in mind again that randomImage in this case should be something like “http://techority.com/image.png”)

    Then in the facebook code rather than doing an actual URL, do;

    1
    picture = myImage
  7. Yeah it makes sense, but how do I set in matters of code that they pick the same random picture? (both my app from the pics that are already in my file and my fb post from URL)

  8. You need the image to be posted from an URL, remember?

    So what you would do is pick from 3 random URLs the image – not from images within your app.

    Does that make sense?

  9. So i have this array:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
        array= {}
    local i = 1
    array[i]= display.newImage("frasefinal/Slide01.png");array[i].alpha=0;i=i+1
    array[i]= display.newImage("frasefinal/Slide02.png");array[i].alpha=0;i=i+1
    array[i]= display.newImage("frasefinal/Slide03.png");array[i].alpha=0;i=i+1
    function selectimage()
    local randomimage = math.random(1,#array)
       array[randomimage].alpha=1
    end
    selectimage()

    how do I set the url to post the one this function above randomly selected?

  10. The image is posted from an URL, so you would upload all the images you wanted then set the URL in the function based on whatever you randomly grabbed.

  11. Ok!
    My last question (promise) is how to post the image I got randomly from an array in the laste scene of my app, and one message on the wall along with it. What should I put in matters of code and what should I leave blank?

  12. Hi Gustavo,

    Where does it say your app is not available? You mean when you click it? If so, yes, it’s fine – it just isn’t showing up because your app isn’t in the store yet.

    Peach :)

  13. So the only thing I need to put on developer.facebook is my apple ID that I get right before uploading my app on itunesconnect?

    I tried that and it says my app is still not available…should I just leave that way?

  14. Hi Peach,

    The app ID required is from iTunes connect or Facebook??
    I didn’t find the HTML 5 that you mentioned at the previous tutorial..
    The apiKey won’t be needed at all?

    Thanks!

    • Hey there, the app ID you add to the code is from Facebook.

      The apiKey isn’t needed at all at this time.

      The HTML5 option is no longer there, so you can ignore that bit.

      Peach :)

  15. Thanks a lot Peach! :D

  16. When you create a page for it in iTunes Connect, but before uploading it, you get given an App ID. (You still have 3 months after that to upload it and still keep your chosen name, if that is your concern.)

    Make sense?

    Peach :)

  17. How do we know our app ID before we submit our app to itunes? Thanks

  18. I believe in the latest daily build it might actually have been fixed; I can’t be certain as I just woke up and have not yet had a chance to look at it properly – but in the release notes for the latest build it appears it might have been addressed :)

  19. Anyword on if Ansca has fixed this for Android yet?

  20. And where do I put the code? What file?

  21. Peach,

    My Basketball Stats is an app I hired a developer to do for me in XCode. Will I be able to use this code with that code? Or will I need to have an app that was developed entirely on Corona SDK?

    • Hi Nick, no – you would need it in Lua, the language Corona uses.

      As to the Facebook code, in main.lua if you are not using Director, in any file that suits you if you are.

      Peach :)

 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.