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)) zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress)) zeroAddress.sin_family = sa_family_t(AF_INET) let defaultRouteReachability = withUnsafePointer(&zeroAddress) { SCNetworkReachabilityCreateWithAddress(nil,UnsafePointer($0)) } var flags: SCNetworkReachabilityFlags = [] if SCNetworkReachabilityGetFlags(defaultRouteReachability!,&flags) == false { return false } let isReachable = flags.contains(.Reachable) let needsConnection = flags.contains(.Connectionrequired) return isReachable && !needsConnection } }
class ViewController: UIViewController { @IBOutlet weak var checkingLabel: UILabel! override func viewDidAppear(animated: Bool) { checkConnectivity() } override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func checkConnectivity() { print(Reachability.isConnectedToNetwork(),terminator: "") if Reachability.isConnectedToNetwork() == false { let alert = UIAlertController(title: "Alert",message: "Internet is not working",preferredStyle: UIAlertControllerStyle.Alert) self.presentViewController(alert,animated: false,completion: nil) let okAction = UIAlertAction(title: "Retry",style: UIAlertActionStyle.Default) { UIAlertAction in alert.dismissViewControllerAnimated(false,completion: nil) //self.checkConnectivity() } alert.addAction(okAction) checkingLabel.text = "" } else { checkingLabel.text = "Connected" } } }没网没有网的时候回弹出警告框