Check for Internet in Corona SDK

Checking for the Internet before accessing the Internet data is the right way to do in any app that you make in any platform.

Here is a small gist to make the network check on Corona SDK. Either use the code in the same Lua file you use or use a separate utility lua file to add the functions. Check here for making the Utility file in Corona SDK (Lua).

local iosNetworkAvailable = true -- 1

function networkListener( event )
    iosNetworkAvailable = event.isReachable
end

if ( network.canDetectNetworkStatusChanges ) then
    network.setStatusListener( "www.apple.com",networkListener ) -- 2
end

function isRechable()
  local os = system.getInfo("platformName")
  if ( os == "iPhone OS") then
      return iosNetworkAvailable -- 3
  elseif ( os == "Android" ) then
    local socket = require("socket") -- 4
    local test = socket.tcp()
    local isNetworkAvailable = false
    test:settimeout(3000) -- Set timeout to 3 seconds
    local testResult = test:connect("www.google.com",80) -- Note that the test does not work if we put http:// in front 
    if not(testResult == nil) then -- 5
      print("Internet access is available")
      isNetworkAvailable = true 
    else
      print("Internet access is not available")
      isNetworkAvailable = false
    end
    test:close() -- 6
    test = nil
    return isNetworkAvailable -- 7
  end
end

Usage :

In the function where you want to check for the utility, just call the function, which will return you the network status.

if isRechable() == true then 
  -- Network is Available Here. Do Something
else 
  -- Network is Not Available Here.
  native.showAlert( "No Internet","It seems internet is not Available. Please connect to internet.", { "OK" } )
end

Code Explanation :

1 — create a local variable.

2 — Create a network listener function available in the network library. Note that this will work only on iOS, so we are using sockets for Android.

3 — we are checking for the Platform and if its iOS, we are sending the status using the network listener which automatically changes the value of the isNetworkAvailable variable.

4 — Using the Sockets to check the internet connection if the platform is Android.

5 — Based on the Socket test result, we are setting the value for the isNetworkAvailable variable.

6 — Close the test connection

7 — return the isNetworkAvailable Variable.

That's for the Network. Happy coding!