I have a small function in Objective-C which uses the C Socket API to check if the device has an active internet connection:
#include <netdb.h> - (BOOL)isNetworkAvailable { char *hostname; struct hostent *hostinfo; hostname = "youtube.com"; hostinfo = gethostbyname(hostname); if (hostinfo == NULL) { return NO; } else { return YES; } }
I have rewritten this function in Swift, using an UnsafeMutablePointer
type for the hostent
struct:
func isNetworkAvailable() -> Bool {
var hostinfo: UnsafeMutablePointer<hostent>
let hostString: String = "youtube.com"
var hostname = (hostString.cStringUsingEncoding(NSUTF8StringEncoding))!
hostinfo = gethostbyname(hostname)
if (hostinfo == nil) {
hostinfo.destroy()
return false
} else {
hostinfo.destroy()
return true
}
}
Is there a better way to check for network connectivity in Swift without using the C API? How can I improve this function, possibly removing the need to manually retain and release an UnsafeMutablePointer
?