Web2py - Corona SDK: Localized Ads in Mobile Apps

DON'T post new tutorials here! Please use the "Pending Submissions" board so the staff can review them first.
Post Reply
User avatar
maboroshi
Dr. Mab
Dr. Mab
Posts: 1624
Joined: 28 Aug 2005, 16:00
18

Web2py - Corona SDK: Localized Ads in Mobile Apps

Post by maboroshi »

I have been working on building a localized ad display feature for a mobile bus schedule software using the Corona SDK and Lua Scripting Language. I am using web2py to generate a json format file for this feature. However any server side web language should be able to handle this.

There won't be to many comments on the steps involved.

Starting with the Web2py

~db.py~

Code: Select all

try:
    import json
except ImportError:
    from gluon.contrib import simplejson as json
~db.py~

Code: Select all

class RESIZE(object): 
    def __init__(self,nx=160,ny=80,error_message='Problem'): 
        (self.nx,self.ny,self.error_message)=(nx,ny,error_message) 
    def __call__(self,value):
        if isinstance(value, str) and len(value)==0: 
            return (value,None) 
        from PIL import Image 
        import cStringIO 
        try: 
            img = Image.open(value.file) 
            img.thumbnail((self.nx,self.ny), Image.ANTIALIAS) 
            s = cStringIO.StringIO() 
            img.save(s, img.format, quality=100) 
            s.seek(0) 
            value.file = s 
        except: 
            return (value, self.error_message) 
        else: 
            return (value, None)

def THUMB(image, nx=320, ny=60):
    from PIL import Image 
    import os
    try:  
        img = Image.open(request.folder + 'static/ads/' + image)
        img.thumbnail((nx,ny), Image.ANTIALIAS) 
        root,ext = os.path.splitext(image)
        thumb='%s_thumb%s' %(root, ext)
        img.save(request.folder + 'static/ads/' + thumb)
        return thumb
    except:
        pass


db.define_table('ads',
                Field('website', requires=IS_EMPTY_OR(IS_URL())),
                Field('phone'),
                Field('localAd', 'upload', uploadfolder=request.folder+'static/ads', label='Business Ad', autodelete=True, requires=IS_EMPTY_OR([IS_IMAGE(extensions=('png', 'gif', 'jpg', 'jpeg')), RESIZE(320, 60)])),
                Field('localAd_thumb', 'upload', compute=lambda r: THUMB(r['localAd'])))
This code is here to resize the images and give some optional values. If you are using web2py you should take notice of where the images are uploaded to. They are being added to the static directory. This makes them visible outside of using the "default", "download" method.

default.py

Code: Select all

@service.json
def ads():
    rows = db(db.ads.id > 0).select(db.ads.website, db.ads.phone, db.ads.localAd, limitby=(0, 1), orderby='<random>')
    return rows
You won't need a view for the above code. The ads controller function will create the appropriate json data and format.

Moving on to Corona SDK!

Create a new main.lua file or add the code below to an existing project

Code: Select all

local widget = require( "widget" )
local json = require("json")
local http = require("socket.http")

local function adNetwork()
	local downloadURL = "http://www.yourdomain.com/missedmybus/static/ads"
	local URL = "http://www.yourdomain.com/missedmybus/default/call/json/ads"

	local response = http.request(URL)

	if response == nil then do
		end
	else
		local data = json.decode(response)
		for i in pairs( data ) do
			adValue = data[i].localAd
			webValue = data[i].website
			phoneValue = data[i].phone
		end
	end

	local url = downloadURL .. "/" .. tostring(adValue)

	local function showNetworkImage(event)
		myTarget = event.target
			
		if ( event.isError ) then do
			 end
		else
			function myTarget:touch( e )
				if e.phase == "began" then
					system.openURL( tostring(webValue) )
					return true
				end
			end
			myTarget:addEventListener( "touch", myTarget )
		end
	end			
	display.loadRemoteImage(url, "GET", showNetworkImage, adValue, system.TemporaryDirectory, display.contentCenterX, display.contentCenterY + 200)
end


You would then need to call the function in your code

Code: Select all

adNetwork()
If you look closely there is a very simple event listener for the ads where you could replace system.openURL( tostring(webValue) ) with system.openURL( "call:" .. tostring(phoneVar) ) or even sms, mailto: etc.

*cheers

Mabo.

Image

User avatar
bad_brain
Site Owner
Site Owner
Posts: 11636
Joined: 06 Apr 2005, 16:00
19
Location: In your eye floaters.
Contact:

Re: Web2py - Corona SDK: Localized Ads in Mobile Apps

Post by bad_brain »

well done buddy, as usual.... =D>

what learning curve Lua has? I kinda always wanted to get into it...but yeah, you know how it is: sidetracked easily... :roll: :lol:
Image

User avatar
maboroshi
Dr. Mab
Dr. Mab
Posts: 1624
Joined: 28 Aug 2005, 16:00
18

Re: Web2py - Corona SDK: Localized Ads in Mobile Apps

Post by maboroshi »

It's a bit of a learning curve but not to much. Python is a lot like Lua I am finding :D

*cheers

Mabo

Post Reply