Thought I’d share this as it might be usual for others.
I needed to detect if I had a good internet connection to prevent my app from hanging when requesting ads on a poor connection. The existing methods only seemed to work if you had a good connection or no connection, so I came up with the below. The code could probably be optimised.
hasInternet = false function networkListener( event ) if ( event.isError ) then timer.cancel(checkTime) hasInternet = false print("NO INTERNET") else timer.cancel(checkTime) print("event.response = " .. event.response) print("time to live = " .. netTime .. "seconds") print("HAS INTERNET") hasInternet = true end end params = {} params.timeout = 3 netTime = 0 function netTimer() netTime = netTime + .1 end checkTime = timer.performWithDelay(100,netTimer,0) checkNet = network.request( "http://www.xxxxxxx.com/check.php", "POST", networkListener,params)
The network request will connect to a php file on my web server, if the server responds within the timeout period, the hasInternet variable is set to true. If it fails to connect or times out the hasInternet variable is left as false. The timer function is for testing purposes so you can work out what to set the timeout to. An acceptable internet connection usually responds in less than 3 seconds, generally 3G is around .75-2
the php code is
\<?php echo "ok"; ?\>
I call this on launch, and on a loading screen between games. I can then use the hasInternet variable to see if I can launch ad’s etc without hanging the app.