ios - Check if internet connection availabile in swift -
ios - Check if internet connection availabile in swift -
this question has reply here:
check net connection in swift 2 (ios 9) 4 answersis there apple framework bundle observe if there's net connection? application crashes when tries geolocate user's position without net connection.
/*inside locationmanager didupdatelocations method*/ var currentlocation:cllocation? = locations[0] as? cllocation geocoder = clgeocoder() //crashes on line below when there isn't net connection //need add together function check if net connection live //before running reversegeocodelocation geocoder.reversegeocodelocation (currentlocation,handlegeocode)
i'm bit new swift , ios programming - apologies.
not full-fledged network checking library found this simple method checking network availability. managed translate swift , here final code.
import foundation import systemconfiguration public class reachability { class func isconnectedtonetwork() -> bool { var zeroaddress = sockaddr_in(sin_len: 0, sin_family: 0, sin_port: 0, sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0)) zeroaddress.sin_len = uint8(sizeofvalue(zeroaddress)) zeroaddress.sin_family = sa_family_t(af_inet) allow defaultroutereachability = withunsafepointer(&zeroaddress) { scnetworkreachabilitycreatewithaddress(nil, unsafepointer($0)).takeretainedvalue() } var flags: scnetworkreachabilityflags = 0 if scnetworkreachabilitygetflags(defaultroutereachability, &flags) == 0 { homecoming false } allow isreachable = (flags & uint32(kscnetworkflagsreachable)) != 0 allow needsconnection = (flags & uint32(kscnetworkflagsconnectionrequired)) != 0 homecoming (isreachable && !needsconnection) ? true : false } }
it works both 3g , wifi connections. i've uploaded github working example. if you're looking simple way check network availability purely in swift, can utilize it.
ios swift
Comments
Post a Comment