1

I am building an app that requires cellular data (3G/4G) at all times.

When my app loads, it checks to see if an internet connection is available. If 'True' it will pull all data from Firebase, else it will show an alert and re-check for a connection via a Timer. See code below for checking for internet connection...

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(MemoryLayout.size(ofValue: zeroAddress))
    zeroAddress.sin_family = sa_family_t(AF_INET)

    let defaultRouteReachability = withUnsafePointer(to: &zeroAddress) {
        $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {zeroSockAddress in
            SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress)
        }
    }

    var flags: SCNetworkReachabilityFlags = SCNetworkReachabilityFlags(rawValue: 0)
    if SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) == false {
        return false
    }

    let isReachable = flags == .reachable
    let needsConnection = flags == .connectionRequired

    return isReachable && !needsConnection
    }
}

I don't really understand this code above in detail. I think it only works for wifi. If wifi is switched off and 3G switched on, it doesn't detect the connection. Can someone help with checking for cellular data please?

M.Strachan
  • 135
  • 2
  • 13
  • The tests for `flags` look wrong. That is an "option set" and values should be tested for containment, not for equality, see for example http://stackoverflow.com/a/25623647/1187415. I don't know if that fixes your problem. – Martin R Jan 23 '17 at 19:23
  • 1
    If you are looking for an alternate solution check out https://github.com/ashleymills/Reachability.swift. It checks if WiFi or Cellular is active – chickenparm Jan 23 '17 at 19:26
  • Possible duplicate of [How can i check mobile data or wifi is on or off. ios swift](http://stackoverflow.com/questions/37919315/how-can-i-check-mobile-data-or-wifi-is-on-or-off-ios-swift) – LordColus Jan 23 '17 at 23:43

0 Answers0