A simple example of determining the network status for iOS
Add SystemConfiguration. framework to the Project
Corresponding. h file
# Import
@ Interface ViewController: UIViewController // If + is added before the method, it is equivalent to a static method of the class. Pay attention to the following-(BOOL) connectedToNetwork; @ end
Corresponding. m file
# Import "ViewController. h" # import
# Import
# Import
# Import
# Import @ interface ViewController () @ end @ implementation ViewController-(void) viewDidLoad {[super viewDidLoad]; UIButton * btn = [[UIButton alloc] init]; btn. frame = CGRectMake (20, 20, 40, 40); btn. backgroundColor = [UIColor brownColor]; [self. view addSubview: btn]; [btn addTarget: self action: @ selector (testOut :) forControlEvents: UIControlEventTouchUpInside]; // Do any additional setup after loading t He view, typically from a nib .} -(BOOL) connectedToNetwork {// Create zero addy struct sockaddr_in zeroAddress; bzero (& zeroAddress, sizeof (zeroAddress); zeroAddress. sin_len = sizeof (zeroAddress); zeroAddress. sin_family = AF_INET; // Recover reachability flags SCNetworkReachabilityRef defaultRouteReachability = SCNetworkReachabilityCreateWithAddress (NULL, (struct sockaddr *) & zeroAddress); SCNetwork ReachabilityFlags flags; BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags (defaultRouteReachability, & flags); CFRelease (defaultRouteReachability); if (! DidRetrieveFlags) {printf ("Error. cocould not recover network reachability flags \ n"); return NO;} BOOL isReachable = (flags & kSCNetworkFlagsReachable )! = 0); BOOL needsConnection = (flags & kSCNetworkFlagsConnectionRequired )! = 0); return (isReachable &&! NeedsConnection )? YES: NO;} // when calling, add the following judgment to the corresponding button:-(IBAction) testOut :( UIButton *) sender {if (! [Self connectedToNetwork]) {UIAlertView * alert = [[UIAlertView alloc] initWithTitle: @ "tip" message: @ "network connection failed. Check whether the network connection is normal! "Delegate: self cancelButtonTitle: @" OK "otherButtonTitles: nil]; [alert show];} NSLog (@" testOut Event ");}-(void) didReceiveMemoryWarning {[super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated .} @ end