Mar 082011
 

This tutorial will show you how to implement Facebook posting in your iPhone application.

I have previously posted a tutorial about using Facebook in your iPhone app, however that method is now depreciated; so here’s the new one!

Follow it exactly and you will be able to post to a Facebook wall easily – if you have any difficulties, just let me know :)

First up, you are going to need to go here and then click “+ Setup New Application” at the top right.

Then fill in the standard info such as your apps name, your email for support, etc. then under mobile and devices be sure to set your core settings to HTML 5 and NOT Native Application.

Next, copy the below code and paste it into your project. If you are not using director, place it near the bottom of main.lua. If you are using director, it will likely go in your gameover.lua or something similar.

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
--------------------------------------------------------------------
local fbButton = display.newImage ("facebook.png")
fbButton.x = 100
fbButton.y = 420
localGroup:insert(fbButton)
-- The above is simply my button to post to Facebook.
------------------------------------------------------------------
-- FACEBOOK --
------------------------------------------------------------------
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 callFacebook = function()
local facebookListener = function( event )
if ( "session" == event.type ) then
if ( "login" == event.phase ) then

local theMessage = "I just took the Zombie Survival Test! I scored " .. score .. " points!"

facebook.request( "me/feed", "POST", {
message=theMessage,
name="Do you think you can beat my score?",
caption="Play YOURAPPNAME now to find out!",
link="http://itunes.apple.com/us/app/your-app-name/id1234567890?mt=8",
picture="http://yoursite.com/yourimage.png" } )
end
end
end
-- Naturally you will want to put your own info above

facebook.login( "1234567890", facebookListener, { "publish_stream" } )
end
-- the above should be your Facebook app ID

local function callFB (event)
if event.phase == "ended" then
callFacebook()
end
end
fbButton:addEventListener("touch", callFB)

Now, go back and edit all that needs editing, as noted with comments.

This code is not something I wrote myself; it is the standard code that everyone uses – I believe I originally found it in the forum and changed it ever so slightly to add a button. I am posting it as I think it helps to get some clarity in an otherwise confusing situation, especially if you have not been successful with Facebook posting previously in your apps, or alternatively if this is your first attempt at implementing Facebook posting using Corona.

The last and most important thing to do here, is to ensure that you place this code at the top of your project file;

1
2
3
4
local ui = require("ui")
local facebook = require("facebook")
local json = require("json")
local tableView = require("tableView")

You do not need to add facebook.lua to your project folder; this will be done automatically when you build your app, however you must add the other three Lua files.

These are already on your computer, find them by opening your Corona folder in Applications, then SampleCode, Networking and finally, Facebook. From here copy tableView.lua, json.lua and ui.lua to your own project folder.

And there you have it!

Your iPhone application should now post to Facebook – try it out! It’s quite exciting, especially the first few times.

Peach Pellen :)

PS – If you’d like a template that includes Facebook posting, you can get one here.

PPS – As usual, if you appreciate my efforts please consider making a donation using the button on the right hand side of the page, liking Techority on Facebook and/or liking/sharing this post- I’d really appreciate it! :)

Like this post? Subscribe to the monthly newsletter!

 

  30 Responses to “Add Facebook Posting To Your Corona iPhone App”

  1. This .. is just so I can get notified when you respond .. spspspspaming!

  2. Ok Peach … I used this code … is awesome. I get no errors.

    However, when the Facebook part comes up the pop up box to approve your usage of the fb app is there for a second and then slides away … nothing to click “yes” or “no” … do you have any idea what’s goin’ on there?

  3. Peach,

    I also am getting errors from following everything step by step.

    maingame.lua:1365: attempt to index global ‘localGroup’ (a nil value)
    stack traceback:
    [C]: ?
    maingame.lua:1365: in function ‘drawGameOverScreen’
    maingame.lua:1516: in function ‘callGameOver’
    maingame.lua:3441: in function ‘_listener’
    ?: in function
    ?: in function

    Im wondering if I inserted the Facebook code in maybe the wrong spot, let me know your thoughts
    thanks peach

  4. hey im not clear with this statement:

    Next, copy the below code and paste it into your project. If you are not using director, place it near the bottom of main.lua. If you are using director, it will likely go in your gameover.lua or something similar.

    what do you mean it will likely go in your gameover.lua or something? Where should I post the code? You mean i can copy + paste the above code in any .lua file if i use director class?

    • You’d paste it into gameover if that is where you were putting your facebook button. Whichever director class file you put your Facebook button into, whichever “scene” or “screen”, that is where you would need this function to go so that the button would work. :)

  5. [...] Integrating Facebook Posting In Your App With Corona  Tutorials  Add comments Nov 182010   Tweet THIS TUTORIAL IS NOW OUTDATED. PLEASE USE THE NEW FACEBOOK TUTORIAL. [...]

  6. [...] Add Facebook Posting To Your iPhone App  Tutorials  Add comments Dec 212010   Tweet THIS TUTORIAL IS NOW DEPRECIATED – PLEASE USE THE UPDATED FACEBOOK TUTORIAL. [...]

  7. One user should post to one Facebook account – however quitting the app and relaunching it will clear it I believe.

  8. what if I want to log out and sign in using other different facebook acount.How can i do that?

  9. No, it is intended to simply close. The user will be logged out automatically after a short time.

  10. I am facing one problem.And the problem is that once i sign in i am not able to sign out.Am i doing something wrong?

  11. That’s a good thing – now you know :) (Could still run it on the Xcode simulator though if you didn’t want to build for device.)

  12. Figured out that it doesn’t work in the simulator =(

  13. Did you require facebook? I don’t think it will work in the simulator. (Because the facebook.lua file is added by Corona during the build.) I’m not certain on that though. Either way make sure you are requiring it. :)

  14. Also I am using the emulator

  15. The file sandbox for this project is located at the following folder:
    (/Users/Kurt/Library/Application Support/Corona Simulator/Crazy Putt-CBE76DEA36949BA4E154106AB1551BFB)
    Runtime error
    /Users/Kurt/Desktop/Crazy Putt/fin.lua:274: attempt to index global ‘facebook’ (a nil value)
    stack traceback:
    [C]: ?
    /Users/Kurt/Desktop/Crazy Putt/fin.lua:274: in function
    ?: in function

    Not sure…. I put my own app ID and I have the latest build??

  16. great tutorial.. I was finished this today

  17. Hey Peach.
    I was just wondering what was the function printTable for? I don’t see any references to it in your code, but perhaps is needed for json ?
    thanks for your tutorial
    cheers

  18. Oh my apologies, I misunderstood your post.

    As I said this code is for iOS only – not for Android. Sorry :(

    Peach

  19. Hello Peach!

    Thanks for the fast reply. I downgraded to build 528 for the android build, cause there were problems with later builds, and carlos from ansca mentioned somewhere in their forum to downgrade to this build.

    The good news is, a friend of mine tested the facebook posting on his HTC Desire, and it worked like a charm.

    The error was posted in my android market developers page and unfortunately, they don´t provide information about the model.

    But it seems, that this is a problem from Ansca not form your code.

    Thanks a lot for your help.

    Greets ,Peter

  20. Hi!

    Thanks a lot for the great code and tutorial. I have added this in my first game. It´s waiting to be approved in AppStore, but already active in Android Market. There i got a system error, with a facebook handler, saying:
    java.lang.NullPointerException
    at com.ansca.corona.Controller.getEventManager(Unknown Source)
    at com.ansca.corona.FacebookRequestListener.onComplete(Unknown Source)
    at com.facebook.android.AsyncFacebookRunner$2.run(AsyncFacebookRunner.java:209)

    I followed the example exactly. Do you know where I went wrong?

    Thank you,

    Peter

  21. Does this cord also work for Android Devices? The facebook app doesn’t need to be published in facebook does it… it just needs to be created so we can get the ID?

    • Sorry but no, this code is written for iOS apps – I don’t currently do Android so I’m not sure of the differences.

      And yes, it just needs to be created for the ID :)

      Peach

  22. Haha, sorry Joseph, I forgot to update. You no longer change any settings on the FB end ^-^;

    Glad you figured it :)

    Peach

  23. Never mind I just went ahead and tested that code without setting anything in Mobile and Devices and it worked great. Thanks for the tutorial!

  24. I’m just starting to implement Facebook posting in my Corona game and I’m having trouble with this instruction:
    under mobile and devices be sure to set your core settings to HTML 5 and NOT Native Application

    When you go to the settings for Mobile and Devices I don’t see anything about HTML 5:
    http://i4.photobucket.com/albums/y120/jhocking/fbdev.png

    What do you need to do?

  25. [...] integration with Facebook and OpenFeint (and now Game Center through the OpenFeint system) are great ways to add even more [...]

  26. I have included something similar in one app, but never thought to share it – beautifully done! Thanks so much for sharing this here, I’m sure many will love it!

    Really, really great comment :D

  27. Great post, Peach. I used this code in my upcoming game “Rico: Mercenary for Hire,” and inserted a little easter egg to reward the player after posting to Facebook. After all, having the player post their score along with the link to your game is free advertising for you which leads to more downloads and sales, so why not reward the player, too?

    Insert this immediately after the facebook.request line:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    if event.isError then
        -- it didn't get posted
        timer.performWithDelay( 500, function() local alert = native.showAlert( "Facebook Error", "Your stats did not get posted on your Wall. Please try again later.", { "OK" } ); end )
    else
        -- posted successfully
        timer.performWithDelay( 500, function() local alert = native.showAlert( "Posted to Facebook", "Your stats have been posted on your Wall.", { "OK" } ); end )
        -- has it been more than 4 hours since they posted last?
        if os.difftime( os.time(), lastFBRewardTime ) >= 14400 then
            lastFBRewardTime = os.time()
            -- reward user with some sort of bonus here
        end
    end

 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.