My project has routines that ask my server for info, and so, if the user does not have Internet, it can not proceed.
So, I need to detect if user has Internet.
I have learned that pinging is restricted in some local networks, so I wrote this which seems to work, but I wonder if Apple tells us the correct way to do it in Cocoa, and if we can access it from ASOC…
Thanks for your comments,
on test_internet_()
try
(**** trying to load my page: ****)
set test_internet to "curl -A 'Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3 (FM Scene 4.6.1)' 'http://www.idanfe.com/you_have_internet.html'"
set has_internet to do shell script test_internet
log "has_internet is: " & has_internet
if has_internet contains "you have internet" then
log "You have Internet connection..."
return true
else
return false
end if
on error
log "You are not connected to the internet"
return false
end try
end test_internet_
Like you have it working now is the best way. You need only internet when you need something from a server, check the ‘cable’ between your machine and the server only. The rest of the world isn’t important. You could use traceroute as an alternative to check if the traced server is actually your server.
I tried to translate Stefan’s code into ASOC as follows:
script InternetTesterAppDelegate
property parent : class "NSObject"
property testAddress : "http://www.idanfe.com/you_have_internet.html"
on applicationWillFinishLaunching_(aNotification)
set theHost to current application's NSString's stringWithString_(testAddress)
set theTarget to current application's SCNetworkReachabilityCreateWithName(missing value, theHost's UTF8String())
set {theBool, theResult} to SCNetworkReachabilityGetFlags(theTarget, reference)
-- do some more stuff with theResult
end applicationWillFinishLaunching_
end script
This didn’t work – I got an error saying that SCNetworkReachabilityCreateWithName was an unknown function. Am I doing something wrong here, or are only foundation functions available from ASOC? I think I’ve tried other non-foundation C-functions that didn’t work either, whereas foundation functions like NSMakeRect do work. I added the SystemConfiguration framework to my project and I’m using Xcode 3 under Lion.
Stefan has given good step-by-step instructions, but there’s a variation to consider. When you make your Objective-C class as per his instructions, instead of making a new instance in MainMenu.xib you can just change the parent of your AS class from “NSObject” to that of the Objective-C class. Then you can call the -hostIsReachable: method as if it is part of your class.