I recently had to make an iPhone app ping a server to check for it, and couldn’t find much helpful code out there. So I cobbled together a small helper which works with the SimplePing old code from apple’s site. Seems to work fine for me. Here’s how you’d use it:

- (void)tapPing {
    [SimplePingHelper ping:@"www.google.com"
        target:self sel:@selector(pingResult:)];
}

- (void)pingResult:(NSNumber*)success {
    if (success.boolValue) {
        [self log:@"SUCCESS"];
    } else {
        [self log:@"FAILURE"];
    }
}

Pretty simple to use – that’s all there is to it. The concept is that you use this as a very simple way of testing if networking will allow you to reach a server.

Keep in mind, that if you’re using this to poll a server to test for network connectivity, it’s probably worth using Reachability to check if they’re not connected to wifi, and if not then don’t ping too often for the sake of the poor old battery!

If it receives a response from the host, it calls pingResult immediately. If it doesn’t get a response, it times out after 1second and calls pingResult with failure.

It takes care of all the memory management for you, so you don’t have to worry about that. It retains target for 1 second, until it cleans up, so there’s no danger of it calling pingResult on a class that has been freed.

Source code can be found on github: https://github.com/chrishulbert/SimplePingHelper

To use it, grab the source and copy the 4 SimplePing* files into your project. Hope it helps someone!

Thanks for reading! And if you want to get in touch, I'd love to hear from you: chris.hulbert at gmail.

Chris Hulbert

(Comp Sci, Hons - UTS)

Software Developer (Freelancer / Contractor) in Australia.

I have worked at places such as Google, Cochlear, Assembly Payments, News Corp, Fox Sports, NineMSN, FetchTV, Coles, Woolworths, Trust Bank, and Westpac, among others. If you're looking for help developing an iOS app, drop me a line!

Get in touch:
[email protected]
github.com/chrishulbert
linkedin



 Subscribe via RSS