in my app i am checking that if mobile data is off its showing the popup like check your data connection. for that i write this 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)
let defaultRouteReachability = withUnsafePointer(&zeroAddress) {
SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, UnsafePointer($0))
}
var flags: SCNetworkReachabilityFlags = SCNetworkReachabilityFlags(rawValue: 0)
if SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) == false {
return false
}
let isReachable = flags == .Reachable
let needsConnection = flags == .ConnectionRequired
return isReachable && !needsConnection
}
}
but by this code its only check that wifi is connected or not. but if i try with 3g mobile data its always showing me that your mobile data is not connected. so how can i solve this?
Try like below code:
Create object of reachability class like,
var internetReachability = Reachability()
Now write below code in viewDidLoad(),
NSNotificationCenter.defaultCenter().addObserver(self, selector: "reachabilityChanged:", name: kReachabilityChangedNotification, object: nil)
self.internetReachability = Reachability.reachabilityForInternetConnection()
self.internetReachability.startNotifier()
self.updateInterfaceWithReachability(self.internetReachability)
Now create function to check reachabilty of wifi as well as data pack,
func updateInterfaceWithReachability(reachability: Reachability)
{
let netStatus : NetworkStatus = reachability.currentReachabilityStatus()
switch (netStatus.rawValue)
{
case NotReachable.rawValue:
print("offline")
break
case ReachableViaWWAN.rawValue:
print("online")
break
case ReachableViaWiFi.rawValue:
print("online")
break
default :
print("offline")
break
}
}
// Rechability update status
func reachabilityChanged(sender : NSNotification!)
{
let curReach : Reachability = sender.object as! Reachability
self.updateInterfaceWithReachability(curReach)
}
Hope this will help you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With